How would you combine useReducer with the Context API to share complex state across many components?
Short answer
You create a reducer to manage the shared state and its update logic, then use Context to make both the current state and the dispatch function available to any component nested inside, without needing to pass them down manually as props through every layer.
Advertisement
AModel answer
You create a reducer to manage the shared state and its update logic, then use Context to make both the current state and the dispatch function available to any component nested inside, without needing to pass them down manually as props through every layer.
const CartContext = React.createContext();
function CartProvider({ children }) {
const [state, dispatch] = useReducer(cartReducer, { items: [] });
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
function useCart() {
return useContext(CartContext);
}Real-world example
A shopping app shares its cart state and update logic across many unrelated components, like the header badge and the checkout page, using a single reducer paired with Context, avoiding the need for prop drilling entirely.
Likely follow-ups
- How is this combination similar to how a library like Redux works internally?
- What happens to performance if this shared context updates very frequently?
Related topics