React
Cart context
Write a provider that wraps the cart reducer with context.
Cart context
This lesson writes the CartProvider component. It takes state and dispatch from useReducer and wraps them in two separate contexts.
CartStateContext holds only state, CartDispatchContext only dispatch. This matters for performance: components using only dispatch don't react to state changes.
Components read state with useContext(CartStateContext) and dispatch with useContext(CartDispatchContext). Multiple components can share the same cart; managed from one place.
Nested Provider
Inside the CartProvider body, two Providers nest: outer CartStateContext.Provider, inner CartDispatchContext.Provider. Content comes from the children prop.
This pattern lets the cart be dispatched from anywhere in the app. A product card calls dispatch({ '{ type: "ADD", payload: product }' }); a summary component reads state.total. The flow is one-way and predictable.
Putting the Provider high in the tree is enough; all sub-components benefit. For multiple carts, use multiple Providers.
Exercise Write CartProvider
Complete the skeleton. Write a CartProvider component. Take ({ '{ children }' }). Call useReducer(cartReducer, { '{ items: [], total: 0 }' }); destructure as [state, dispatch]. Return <CartStateContext.Provider value={ '{ state }' }> wrapping <CartDispatchContext.Provider value={ '{ dispatch }' }>{ '{ children }' }</CartDispatchContext.Provider></CartStateContext.Provider>. Export it.
Show example solution
import { useReducer, createContext } from "react";
const CartStateContext = createContext(null);
const CartDispatchContext = createContext(null);
function CartProvider({ children }) {
const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
return (
<CartStateContext.Provider value={state}>
<CartDispatchContext.Provider value={dispatch}>
{children}
</CartDispatchContext.Provider>
</CartStateContext.Provider>
);
}
export default CartProvider;
Test yourself
-
What does CartStateContext carry?
- items
- dispatch
- actions
- state
Show answer
state — CartStateContext carries state.
-
Why two contexts
Two contexts are used for ____.
Show answer
Two contexts are used for performance.
-
Match the CartProvider parts
- useReducer
- [state, dispatch]
- CartStateContext
- state
- CartDispatchContext
- dispatch
- children
- content
Next lesson: Add product UI