Part 10 / Topic 7 of 8
A preview: pairing useReducer with context
Part 9 is where context itself - createContext, a Provider, the custom-hook-with-a-safety-throw idiom - is taught in full. What is new here is only where the reducer lives. examples/06_reducer_context_preview.jsx's CartStoreProvider calls useReducer exactly once, and both cart and dispatch travel down through context to any descendant that calls useCartStore():
// examples/06_reducer_context_preview.jsx
const CartStoreContext = createContext(undefined);
export function CartStoreProvider({ children }) {
const [cart, dispatch] = useReducer(cartReducer, initialCart);
return <CartStoreContext.Provider value={{ cart, dispatch }}>{children}</CartStoreContext.Provider>;
}
export function useCartStore() {
const store = useContext(CartStoreContext);
if (store === undefined) {
throw new Error("useCartStore must be called inside a <CartStoreProvider>");
}
return store;
}
CartAddControl, CartItemList, and CartSummaryBadge are three siblings that each call useCartStore() for only what they need - none of them receives cart or dispatch as a prop from any of the others. Rendering all three together and clicking "Add Butter Naan" twice really updates CartItemList's row and CartSummaryBadge's count from one dispatch call each time (examples/06_reducer_context_preview.test.jsx); calling useCartStore() from outside any CartStoreProvider really throws the clear, specific error instead of crashing later on undefined.cart. One useReducer call behind one Provider, read through one custom hook, is the entire shape of the "poor man's Redux" pattern this course's project (next) builds for real, and the shape a real state management library (Zustand, Redux Toolkit - Stage 5) later formalizes with more tooling around the same idea.
Done here? The practice set for Part 10 — including the solutions — is on the part page.