Using the Context APIs

Learn to use the Context APIs for global and local state management.

With React v16.3.0, released back in 2018, we finally got access to stable Context APIs. They give us a straightforward way to share data between all the components inside a given context without explicitly having to pass it via props from one component to another, even from children to a parent component. We highly recommend reading the official React documentation if you want to learn more about React Context.

Starting with this lesson, we'll always use the same boilerplate codeBoilerplate code is reusable, standard code serving as a template. for approaching global state management with different libraries.

Click the “Run” button below to execute the code. Once the execution is completed, observe the output by navigating to the link provided at the bottom of the playground.

# cd /usercode/boilerplate
# npm install --force
# npm run dev

# ln -s /app/node_modules/ /usercode/API 
# cd /usercode/API
# node index.js >/dev/null 2>&1 &

# Frontend setup
export PORT=5000
ln -s /app/node_modules/ /usercode/boilerplate 
cd /usercode/boilerplate
npm run dev

Starting template for e-commerce app

Note: The “+” and “-” buttons won’t work in this code. We’ll implement the functionality shortly.

We’ll also keep the same approach for storing the selected products in the global state for simplicity’s sake; our state will be a JavaScript object. Each property is the ID of a product, and its value will represent the number of products that the user has selected. If we open the data/items.js file, we’ll find an array of objects representing our products. If a user selects four carrots and two onions, our state will look like this:

{
"8321-k532":4,
"9126-b921":2
}
Products in the cart

Creating the shopping cart context

That being said, let’s start by creating the context for our shopping cart. We can do that by creating a new file, ... ...