How do you share state between multiple components that are not directly related, such as a shopping cart shown in both the header and a product page?
Short answer
You use React Context to create a shared piece of state accessible from any component wrapped inside its provider, avoiding the need to pass that data down manually through many layers of unrelated components, which is especially useful for things like a shopping cart, theme…
Advertisement
AModel answer
You use React Context to create a shared piece of state accessible from any component wrapped inside its provider, avoiding the need to pass that data down manually through many layers of unrelated components, which is especially useful for things like a shopping cart, theme setting, or logged in user information.
'use client';
import { createContext, useContext, useState } from 'react';
const CartContext = createContext(null);
export function CartProvider({ children }) {
const [items, setItems] = useState([]);
return <CartContext.Provider value={{ items, setItems }}>{children}</CartContext.Provider>;
}
export function useCart() {
return useContext(CartContext);
}Real-world example
An online store shares the shopping cart state between its header icon showing the item count and the actual cart page itself, using a single context provider that wraps the entire application.
Likely follow-ups
- Where should a context provider be placed in the App Router's layout structure?
- Does using context negatively affect performance for a large application?
Related topics