Thought of putting out something short as a way to practice my writing. I wrote this without research or much planning, but I hope it will help someone out there.
Have you worked with a React app that needed the same data in multiple components? If you have worked with something larger than a to-do app, the odds are yes, you have. How would you pass down the data? Store the data higher up in React state and pass them down to child components (and sometimes their children) via props? Reach out to Redux (or Mobx etc.)? Or do you have some other way? React has now introduced something in core that you can make use of. It’s called React Context.
Context has two main parts:
- Provider – where the data is fed.
- Consumer – where the data is used.
Creating a React Context
To create a context, you have to use the React.createContext
method:
export const CartContext = new React.createContext({});
In the above code sample, we are creating a context. We can pass default values as arguments if we want. In this case, I’m just passing an empty object.
Using the Context
We have to wrap the parent component or any component above it within CartContext.Provider
in order to use the data inside a child component:
<CartContext.Provider value={{ itemCount: 2 }}>
<Cart />
</CartContext.Provider>
In the above sample, we are passing a value for the property itemCount
as 2
.
Let’s see how to consume the itemCount
inside of the Cart component or even inside of its child:
const Cart = () => {
const cartData = React.useContext(CartContext);
return (
<div>
<h2>Cart</h2>
{cartData.itemCount}
</div>
);
};
That would display 2
inside the Child component! We also just used React Hooks (useContext
), congratulations!
Leave a Reply