Using Context in React
Introduction
When we need to pass data from a parent component to a child component, we can use props. However, when we need to pass data from a grandparent component to a grandchild component, we have to pass the data all the way down through props, which can become cumbersome and difficult to manage. This is where React Context comes in handy.
What is Context?
Context is a way to share data between components without having to pass props down manually at every level. It allows us to create a global state that can be accessed by any component in the component tree.
If you familiar with Redux, Zustand, or other state management libraries, you can think of Context as a simpler alternative for managing global state in React applications.
Creating a Context
Let’s create a context called ProductContext that will hold an array of products.
React context files are usually placed in a
contextfolder in thesrcdirectory. You can create a new file calledProductContext.tsxin thecontextfolder.
import { createContext, useState, useContext, type ReactNode } from "react";
interface Product {
id: number;
name: string;
}
interface ContextValue {
products: Product[];
setProducts: (products: Product[]) => void;
}
// 1. Create the context
const ProductContext = createContext<ContextValue | undefined>(undefined);
// 2. Create the provider component
export function ProductContextProvider({ children }: { children: ReactNode }) {
const [products, setProducts] = useState<Product[]>([]);
const value = { products, setProducts };
return <ProductContext value={value}>{children}</ProductContext>;
}
// 3. Create a custom hook to use the context
export function useProductContext() {
const context = useContext(ProductContext);
if (!context) {
throw new Error(
"useProductContext must be used within a ProductContextProvider",
);
}
return context;
}There are a lot of things happening in the above code snippet, so let’s break it down step by step.
ProductandContextValueare TypeScript interfaces that define the shape of the product data and the context value, respectively.ProductContextis created using thecreateContext()function, which takes an initial value ofundefined.ProductContextProvideris a component that uses theuseState()hook to manage the state of the products and provides the context value to its children. It takes achildrenprop, which is the content that will be wrapped by the provider.useProductContextis a custom hook that allows us to access the context value from any component that is a descendant of theProductContextProvider. It throws an error if it is used outside of the provider, ensuring that we are always using the context correctly.
Get Ye Min Ko’s stories in your inbox
Join Medium for free to get updates from this writer.
Providing the Context
Creating a context alone is not enough. We need to wrap our component tree with the ProductContextProvider so that all components can access the context value. Go to App component and wrap the component tree with the ProductContextProvider like this:
export default function App() {
return (
<ProductContextProvider>
<Products />
<GetProducts />
</ProductContextProvider>
);
}Using the Context
Now that we have provided the context, we can use it in any component that is a descendant of the ProductContextProvider. Let's see how we can use the context in the Products and GetProducts components.
Products Component
In the Products component, we will use the useProductContext hook to access the products from the context and display them. If there are no products available, we will display a message indicating that.
export default function Products() {
const { products } = useProductContext();
return (
<>
{products.length === 0 && <div>No products available</div>}
<div>
{products.map((product) => (
<div key={product.id}>{product.name}</div>
))}
</div>
</>
);
}GetProducts Component
In the GetProducts component, we will use the useProductContext hook to access the setProducts function from the context. When the button is clicked, we will set the products in the context, which will trigger a re-render of the Products component and display the newly added products.
export default function GetProducts() {
const { setProducts } = useProductContext();
function handleProducts() {
setProducts([
{ id: 1, name: "Product 1" },
{ id: 2, name: "Product 2" },
{ id: 3, name: "Product 3" },
]);
}
return <button onClick={handleProducts}>Get Products</button>;
}Notice that in App component, Products and GetProducts components does not pass any props to each other, but they can still communicate through the context. When the button in GetProducts is clicked, it updates the products in the context, and the Products component automatically re-renders to display the new products.
Conclusion
React Context is useful for sharing data between components without having to pass props down manually at every level. It allows us to create a global state that can be accessed by any component in the component tree. However, if you need to manage complex state that need frequent updates, you might want to consider using a state management library like Zustand or Redux instead of Context.







