Context with reducer
Overview
You’ve learned two tools separately: reducers consolidate update logic, and context delivers values deep into the tree. Together they make a simple, built-in way to manage app-wide state — such as a shopping cart that the header badge, the course cards and the checkout page all use.
Step 1: The reducer
// cart/cartReducer.js
export const initialCart = { items: [] };
export function cartReducer(cart, action) {
switch (action.type) {
case 'added': {
const existing = cart.items.find((i) => i.id === action.course.id);
const items = existing
? cart.items.map((i) => (i.id === action.course.id ? { ...i, qty: i.qty + 1 } : i))
: [...cart.items, { ...action.course, qty: 1 }];
return { ...cart, items };
}
case 'removed':
return { ...cart, items: cart.items.filter((i) => i.id !== action.id) };
case 'cleared':
return initialCart;
default:
throw new Error(`Unknown action: ${action.type}`);
}
}Step 2: Two contexts
// cart/CartContext.jsx
import { createContext, useContext, useReducer } from 'react';
import { cartReducer, initialCart } from './cartReducer.js';
const CartContext = createContext(null);
const CartDispatchContext = createContext(null);Why two? Many components only send actions (“Add to cart” buttons) and never display the cart. React guarantees that dispatch is the same function on every render, so a context holding only dispatch never changes, and its consumers never re-render because of cart updates.
Step 3: The provider component
export function CartProvider({ children }) {
const [cart, dispatch] = useReducer(cartReducer, initialCart);
return (
<CartContext value={cart}>
<CartDispatchContext value={dispatch}>
{children}
</CartDispatchContext>
</CartContext>
);
}Step 4: Hooks for consumers
export function useCart() {
const cart = useContext(CartContext);
if (!cart) throw new Error('useCart must be used inside <CartProvider>');
return cart;
}
export function useCartDispatch() {
const dispatch = useContext(CartDispatchContext);
if (!dispatch) throw new Error('useCartDispatch must be used inside <CartProvider>');
return dispatch;
}Step 5: Use it anywhere
// main.jsx
<CartProvider>
<App />
</CartProvider>function CartBadge() {
const { items } = useCart();
const count = items.reduce((n, i) => n + i.qty, 0);
return <span className="badge">🛒 {count}</span>;
}
function CourseCard({ course }) {
const dispatch = useCartDispatch();
return (
<article>
<h2>{course.title}</h2>
<button onClick={() => dispatch({ type: 'added', course })}>Add to cart</button>
</article>
);
}
function CheckoutPage() {
const { items } = useCart();
const dispatch = useCartDispatch();
const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
return (
<section>
{items.map((i) => (
<p key={i.id}>
{i.title} × {i.qty}
<button onClick={() => dispatch({ type: 'removed', id: i.id })}>Remove</button>
</p>
))}
<p>Total: ${total.toFixed(2)}</p>
</section>
);
}CartBadge, CourseCard and CheckoutPage can be anywhere in the app — no props pass through Layout, Header or CourseGrid.
Optional: action helpers
Instead of exposing raw dispatch, you can expose named functions, which some teams find friendlier:
export function useCartActions() {
const dispatch = useCartDispatch();
return {
add: (course) => dispatch({ type: 'added', course }),
remove: (id) => dispatch({ type: 'removed', id }),
clear: () => dispatch({ type: 'cleared' }),
};
}Persisting the cart
To keep the cart after a page reload, initialise from localStorage and save with an effect — the cart is syncing with an external system (storage), so this is a legitimate effect:
export function CartProvider({ children }) {
const [cart, dispatch] = useReducer(cartReducer, initialCart, (init) => {
try {
return JSON.parse(localStorage.getItem('cart')) ?? init;
} catch {
return init;
}
});
useEffect(() => {
localStorage.setItem('cart', JSON.stringify(cart));
}, [cart]);
// …providers as before
}Limits of this pattern
Context + reducer is great for small and medium apps. Watch for these signs that you’ve outgrown it:
- Every consumer re-renders on every change. A component that only needs the item count still re-renders when a quantity changes. With a lot of consumers or frequent updates, this adds up.
- Many unrelated slices (cart, user, notifications, filters…) each need their own provider, and the providers stack up in
main.jsx. - Server data creeps in. Course lists, enrolments and profiles fetched from an API belong in a data-fetching cache, not a reducer — see TanStack Query.
The next lesson covers external stores, which let components subscribe to just the slice they need.
Rule of thumb: UI state that many components share → context + reducer. Server data → a fetching library. Very frequently changing or large global state → an external store.
A cart available everywhere
Build a CartProvider using useReducer with the cartReducer from the useReducer lesson (or a simple version supporting added and removed). Provide the cart and dispatch in two separate contexts, and export useCart() and useCartDispatch() hooks. Then build a CartBadge that shows the number of items, and an AddToCartButton({ course }) that dispatches added — and check that AddToCartButton doesn’t need to re-render when the cart changes.
import { createContext, useContext, useReducer } from 'react';
const CartContext = createContext(null);
const CartDispatchContext = createContext(null);
export function CartProvider({ children }) {
// your code here
}import { createContext, useContext, useReducer } from 'react';
const CartContext = createContext(null);
const CartDispatchContext = createContext(null);
function cartReducer(cart, action) {
switch (action.type) {
case 'added': {
const existing = cart.items.find((i) => i.id === action.course.id);
const items = existing
? cart.items.map((i) => (i.id === action.course.id ? { ...i, qty: i.qty + 1 } : i))
: [...cart.items, { ...action.course, qty: 1 }];
return { ...cart, items };
}
case 'removed':
return { ...cart, items: cart.items.filter((i) => i.id !== action.id) };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export function CartProvider({ children }) {
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
return (
<CartContext value={cart}>
<CartDispatchContext value={dispatch}>{children}</CartDispatchContext>
</CartContext>
);
}
export function useCart() {
const cart = useContext(CartContext);
if (!cart) throw new Error('useCart must be used inside <CartProvider>');
return cart;
}
export function useCartDispatch() {
const dispatch = useContext(CartDispatchContext);
if (!dispatch) throw new Error('useCartDispatch must be used inside <CartProvider>');
return dispatch;
}
export function CartBadge() {
const { items } = useCart();
const count = items.reduce((n, i) => n + i.qty, 0);
return <span aria-label={`${count} items in cart`}>🛒 {count}</span>;
}
export function AddToCartButton({ course }) {
// Reads only dispatch, which never changes, so cart updates don't re-render it
const dispatch = useCartDispatch();
return <button onClick={() => dispatch({ type: 'added', course })}>Add {course.title}</button>;
}Summary
- A reducer manages the state; context delivers state and dispatch to any component below the provider.
- Put state and dispatch in separate contexts —
dispatchnever changes, so dispatch-only components don’t re-render. - Wrap it all in one provider component and expose custom hooks like
useCart()anduseCartDispatch(). - Components dispatch actions describing events; all update logic stays in the reducer.
- This pattern scales to medium apps; for high-frequency updates or many slices, consider an external store.