Lab: Untangle a Prop-Drilled Cart
Refactor a prop-drilled shop page end to end: a typed cart reducer with unit tests, state and dispatch in split contexts, filters in the URL, and a cross-page preference in a hand-rolled store.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: feel the drilling
- Step 2: the cart becomes a typed reducer
- Step 3: share it through split contexts
- Step 4: filters move to the URL
- Step 5: a cross-page preference in a module store
- Step 6: document the placements
- Check your understanding
- Apply it
- Review prompt
Lessons of Frontend State Management
- Where Should This State Live? Concept · 20 min
- Reducers for Complex Transitions Worked example · 25 min
- Context Without the Re-render Tax Concept · 20 min
- External Stores and Selectors Worked example · 25 min
- Lab: Untangle a Prop-Drilled Cart Lab · 30 min
- Check: State Placement Scenarios Knowledge check · 6 questions
What you will learn
- Classify application state as local UI, shared client, URL or server state, and justify where each piece should live.
- Model complex state transitions with useReducer and typed actions, and share them through context without unnecessary re-renders.
- Implement global client state with an external store such as Zustand or Redux Toolkit using selectors, and explain when a store is warranted over context.
Prerequisites: React Components & State
01. Goal and setup
This lab assembles the whole skill on one page. You start from a shop that works — but its cart state is drilled through every tier, its category filter has no home that survives a reload, and its currency choice would be drilled too if a second page existed. You finish with each value in the home the first lesson named: cart transitions in a typed reducer (the pattern from the reducer lesson), shared through split contexts (the context lesson); filters in the URL; a cross-page currency in a module store with selector subscriptions (the external store lesson).
You need: Node 22 or later with npm, and an empty folder. Everything here runs under Vitest with jsdom (a simulated browser DOM), so no dev server is needed; to see the page in a browser as well, drop the src files into a Vite React project such as the one the tooling lab builds. The lab was checked on 26 November 2026 with React 19.3.1, Vitest 5.1.2, jsdom 31.0.1, @testing-library/react 16.3.3, @testing-library/dom 10.4.2 and @testing-library/user-event 14.6.13. No state library is installed: the store is twenty lines you write yourself.
mkdir cart-lab && cd cart-lab
npm init -y && npm pkg set type=module
npm install [email protected] [email protected]
npm install -D [email protected] [email protected] @testing-library/[email protected] \
@testing-library/[email protected] @testing-library/[email protected]vitest.config.ts
src/
├── products.ts three products, one type
├── log.ts the render log every component writes to
├── BeforeApp.tsx the drilled page (step 1)
├── before.test.tsx prints its render log (step 1)
├── cart.ts the reducer (step 2)
├── cart.test.ts four reducer tests (step 2)
├── cart-context.tsx provider and hooks (step 3)
├── App.tsx the page after the refactor (step 3)
├── after.test.tsx prints its render logs (steps 3 to 5)
├── url-state.ts URL search params as state (step 4)
└── currency.ts module store for currency (step 5)vitest.config.ts picks jsdom for every test file. Each component calls log() at the top of its body, and the two test files render the pages, click like a user and print the log — so every expected output below is a render log you can reproduce exactly. In a real app you would console.log in the component body while developing; collecting the lines in an array just lets a test print them in order.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: { environment: 'jsdom' },
});export type Product = {
sku: string;
name: string;
category: 'Bakery' | 'Fruit' | 'Veg';
pricePence: number;
};
export const products: Product[] = [
{ sku: 'B01', name: 'Bagels', category: 'Bakery', pricePence: 190 },
{ sku: 'F01', name: 'Apples', category: 'Fruit', pricePence: 180 },
{ sku: 'V01', name: 'Carrots', category: 'Veg', pricePence: 70 },
];
// src/log.ts
// Every component calls log() at the top of its body; tests read the list.
export const renders: string[] = [];
export function log(line: string): void {
renders.push(line);
}02. Step 1: feel the drilling
The starting page keeps the cart in BeforeApp and passes cart and onAdd down through Header and ProductGrid to every row and every button. Nothing is wrong functionally — the badge updates. The cost is structural:
import { useState } from 'react';
import { log } from './log';
import { products, type Product } from './products';
type CartLine = { sku: string; qty: number };
type AddFn = (product: Product) => void;
function AddButton({ product, onAdd }: { product: Product; onAdd: AddFn }) {
log(`render AddButton ${product.sku}`);
return (
<button type="button" onClick={() => onAdd(product)}>
Add {product.name}
</button>
);
}
function ProductRow({ product, onAdd }: { product: Product; onAdd: AddFn }) {
log(`render ProductRow ${product.sku}`);
return (
<li>
{product.name} <AddButton product={product} onAdd={onAdd} />
</li>
);
}
function ProductGrid({ onAdd }: { onAdd: AddFn }) {
log('render ProductGrid');
return (
<ul>
{products.map((p) => (
<ProductRow key={p.sku} product={p} onAdd={onAdd} />
))}
</ul>
);
}
function Header({ cart, onAdd }: { cart: CartLine[]; onAdd: AddFn }) {
log('render Header');
return (
<header>
<p role="status">{cart.reduce((n, l) => n + l.qty, 0)} items</p>
<ProductGrid onAdd={onAdd} />
</header>
);
}
export function BeforeApp() {
const [cart, setCart] = useState<CartLine[]>([]);
log('render BeforeApp');
function onAdd(product: Product) {
setCart((prev) =>
prev.some((l) => l.sku === product.sku)
? prev.map((l) => (l.sku === product.sku ? { ...l, qty: l.qty + 1 } : l))
: [...prev, { sku: product.sku, qty: 1 }],
);
}
return <Header cart={cart} onAdd={onAdd} />;
}import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { it } from 'vitest';
import { BeforeApp } from './BeforeApp';
import { renders } from './log';
it('one click on the drilled page', async () => {
const user = userEvent.setup();
render(<BeforeApp />);
renders.length = 0; // forget the mount, keep the click
await user.click(screen.getByRole('button', { name: 'Add Apples' }));
console.log(renders.join('\n'));
});Before you run the test, predict how many lines one click will print, and which components they will name.
stdout | src/before.test.tsx > one click on the drilled page
render BeforeApp
render Header
render ProductGrid
render ProductRow B01
render AddButton B01
render ProductRow F01
render AddButton F01
render ProductRow V01
render AddButton V01That is nine components for one click: the app, two relay tiers that read nothing they pass on, three rows, three buttons. Two of the nine want the news (the badge, and BeforeApp, which owns the state); seven are bystanders. Steps 2 to 5 separate them.
03. Step 2: the cart becomes a typed reducer
export type CartLine = {
sku: string;
name: string;
pricePence: number;
qty: number;
};
export type CartState = { lines: CartLine[] };
export const emptyCart: CartState = { lines: [] };
export type CartAction =
| { type: 'add'; sku: string; name: string; pricePence: number }
| { type: 'setQty'; sku: string; qty: number }
| { type: 'clear' };
export function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case 'add': {
const line = state.lines.find((l) => l.sku === action.sku);
if (line) {
return {
...state,
lines: state.lines.map((l) =>
l.sku === action.sku ? { ...l, qty: l.qty + 1 } : l,
),
};
}
return {
...state,
lines: [
...state.lines,
{
sku: action.sku,
name: action.name,
pricePence: action.pricePence,
qty: 1,
},
],
};
}
case 'setQty': {
if (action.qty <= 0) {
return { ...state, lines: state.lines.filter((l) => l.sku !== action.sku) };
}
return {
...state,
lines: state.lines.map((l) =>
l.sku === action.sku ? { ...l, qty: action.qty } : l,
),
};
}
case 'clear':
return emptyCart;
}
}
export const cartTotalPence = (lines: CartLine[]): number =>
lines.reduce((sum, l) => sum + l.pricePence * l.qty, 0);Same shape as the upload queue: one status per line is implicit in the data (a line exists once per SKU), every branch builds a new state, and the exhaustive switch means a new action fails to compile until it is handled. Now prove the transitions before any component runs:
import { describe, expect, it } from 'vitest';
import { cartReducer, cartTotalPence, emptyCart, type CartAction } from './cart';
const apples: CartAction = { type: 'add', sku: 'F01', name: 'Apples', pricePence: 180 };
const bagels: CartAction = { type: 'add', sku: 'B01', name: 'Bagels', pricePence: 190 };
describe('cartReducer', () => {
it('adds a new line and then merges repeat adds into it', () => {
const cart = cartReducer(cartReducer(emptyCart, apples), apples);
expect(cart.lines.map((l) => `${l.sku} x${l.qty}`)).toEqual(['F01 x2']);
});
it('removes the line when the quantity reaches zero', () => {
let cart = cartReducer(emptyCart, bagels);
cart = cartReducer(cart, { type: 'setQty', sku: 'B01', qty: 0 });
expect(cart.lines).toEqual([]);
});
it('never edits the previous state', () => {
const before = cartReducer(emptyCart, apples);
const after = cartReducer(before, apples);
expect(before.lines[0].qty).toBe(1);
expect(after).not.toBe(before);
});
it('derives the total from the lines', () => {
const cart = cartReducer(cartReducer(emptyCart, apples), apples);
expect(cartTotalPence(cart.lines)).toBe(360);
});
}); ✓ src/cart.test.ts (4 tests)
Test Files 1 passed (1)
Tests 4 passed (4)The four tests cover merging repeat adds, quantity removal, the immutable-update rule (the previous state object stays untouched) and the derived total (two Apples at 180 pence make 360). The cartTotalPence helper — a reduce over lines — is deliberately a function, not stored state: the total is derived, as the placement lesson insists.
04. Step 3: share it through split contexts
The provider replaces BeforeApp as the owner of the cart, and the split from the context lesson comes straight across, written with the React 19 spelling in which the context object itself is the provider:
import { createContext, useContext, useReducer, type ReactNode } from 'react';
import { cartReducer, emptyCart, type CartAction, type CartState } from './cart';
const CartStateContext = createContext<CartState | null>(null);
const CartDispatchContext =
createContext<((action: CartAction) => void) | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [cart, dispatch] = useReducer(cartReducer, emptyCart);
return (
<CartDispatchContext value={dispatch}>
<CartStateContext value={cart}>
{children}
</CartStateContext>
</CartDispatchContext>
);
}
export function useCartState(): CartState {
const cart = useContext(CartStateContext);
if (!cart) throw new Error('useCartState needs <CartProvider>');
return cart;
}
export function useCartDispatch() {
const dispatch = useContext(CartDispatchContext);
if (!dispatch) throw new Error('useCartDispatch needs <CartProvider>');
return dispatch;
}The new page reads the cart through those hooks: CartBadge and CartSummary (which formats the derived total) call useCartState; each AddToCart button calls only useCartDispatch. The page also uses the URL module of step 4 and the currency store of step 5, so create src/url-state.ts and src/currency.ts from those steps now; they are short, and the steps explain them.
import { cartTotalPence } from './cart';
import { CartProvider, useCartDispatch, useCartState } from './cart-context';
import { setCurrency, useCurrency, type Currency } from './currency';
import { log } from './log';
import { products, type Product } from './products';
import { setParam, useSearchParam } from './url-state';
const RATES: Record<Currency, number> = { GBP: 1, EUR: 1.16 };
const SYMBOLS: Record<Currency, string> = { GBP: '£', EUR: '€' };
const money = (pence: number, c: Currency) =>
`${SYMBOLS[c]}${((pence * RATES[c]) / 100).toFixed(2)}`;
function CartBadge() {
const cart = useCartState();
log('render CartBadge');
return <p role="status">{cart.lines.reduce((n, l) => n + l.qty, 0)} items</p>;
}
function CartSummary() {
const cart = useCartState();
const currency = useCurrency();
log('render CartSummary');
return <p>Total: {money(cartTotalPence(cart.lines), currency)}</p>;
}
function CurrencyPicker() {
const currency = useCurrency();
log(`render CurrencyPicker (${currency})`);
return (
<label>
Currency{' '}
<select
value={currency}
onChange={(e) => setCurrency(e.target.value as Currency)}
>
<option>GBP</option>
<option>EUR</option>
</select>
</label>
);
}
function CategoryFilter() {
const category = useSearchParam('category');
log(`render CategoryFilter (${category || 'all'})`);
return (
<label>
Category{' '}
<select value={category} onChange={(e) => setParam('category', e.target.value)}>
<option value="">All</option>
<option>Bakery</option>
<option>Fruit</option>
<option>Veg</option>
</select>
</label>
);
}
function Price({ pence }: { pence: number }) {
const currency = useCurrency();
log(`render Price ${pence}`);
return <span>{money(pence, currency)}</span>;
}
function AddToCart({ product }: { product: Product }) {
const dispatch = useCartDispatch();
log(`render AddToCart ${product.sku}`);
const { sku, name, pricePence } = product;
const add = () => dispatch({ type: 'add', sku, name, pricePence });
return (
<button type="button" onClick={add}>
Add {name}
</button>
);
}
function ProductRow({ product }: { product: Product }) {
log(`render ProductRow ${product.sku}`);
return (
<li>
{product.name} <Price pence={product.pricePence} />{' '}
<AddToCart product={product} />
</li>
);
}
function ProductGrid() {
const category = useSearchParam('category');
log(`render ProductGrid (${category || 'all'})`);
const visible = products.filter((p) => !category || p.category === category);
return (
<ul>
{visible.map((p) => (
<ProductRow key={p.sku} product={p} />
))}
</ul>
);
}
export function AfterApp() {
log('render AfterApp');
return (
<CartProvider>
<header>
<CartBadge />
<CartSummary />
<CurrencyPicker />
</header>
<main>
<CategoryFilter />
<ProductGrid />
</main>
</CartProvider>
);
}import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, expect, it } from 'vitest';
import { AfterApp } from './App';
import { renders } from './log';
const take = () => renders.splice(0); // read the log and empty it
afterEach(() => {
cleanup();
window.history.replaceState(null, '', '/');
});
it('step 3: mount, add, add', async () => {
const user = userEvent.setup();
render(<AfterApp />);
await user.click(screen.getByRole('button', { name: 'Add Apples' }));
await user.click(screen.getByRole('button', { name: 'Add Apples' }));
console.log(take().join('\n'));
});
it('step 4: the category lives in the URL', async () => {
const user = userEvent.setup();
const filter = () => take().filter((line) => line.includes('CategoryFilter'));
window.history.replaceState(null, '', '/?category=Fruit');
render(<AfterApp />);
const out = [...filter(), `URL after load: ${window.location.search}`];
await user.selectOptions(screen.getByLabelText('Category'), 'Bakery');
out.push(...filter(), `URL after pick: ${window.location.search}`);
window.history.back();
await screen.findByRole('button', { name: 'Add Apples' });
out.push(...filter(), `URL after back: ${window.location.search}`);
console.log(out.join('\n'));
});
it('step 5: one currency switch', async () => {
const user = userEvent.setup();
render(<AfterApp />);
await user.click(screen.getByRole('button', { name: 'Add Apples' }));
await user.click(screen.getByRole('button', { name: 'Add Apples' }));
take();
await user.selectOptions(screen.getByLabelText('Currency'), 'EUR');
console.log(take().join('\n'));
expect(screen.getByText('Total: €4.18')).toBeTruthy();
});Because CartProvider renders {children} and those child elements were created by AfterApp, outside the provider, React bails out of re-rendering them when the cart changes — only the components that read CartStateContext re-render. Predict the log for two clicks on "Add Apples" before you run it:
npx vitest run src/after.test.tsx -t "step 3"stdout | src/after.test.tsx > step 3: mount, add, add
render AfterApp
render CartBadge
render CartSummary
render CurrencyPicker (GBP)
render CategoryFilter (all)
render ProductGrid (all)
render ProductRow B01
render Price 190
render AddToCart B01
render ProductRow F01
render Price 180
render AddToCart F01
render ProductRow V01
render Price 70
render AddToCart V01
render CartBadge
render CartSummary
render CartBadge
render CartSummaryCompare with step 1: nine renders per click, now two — the badge and the summary, the only components that read the changed state. AddToCart F01, which was clicked, does not appear again: it subscribes to dispatch, whose identity never changes.
05. Step 4: filters move to the URL
The category filter is view state that should survive a reload and travel in links, so its home is the URL — not the component, not the cart. A tiny module keeps the mechanics in one place:
import { useSyncExternalStore } from 'react';
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
window.addEventListener('popstate', listener);
listeners.add(listener);
return () => {
window.removeEventListener('popstate', listener);
listeners.delete(listener);
};
}
export function setParam(key: string, value: string): void {
const params = new URLSearchParams(window.location.search);
if (value) params.set(key, value);
else params.delete(key);
const query = params.toString();
window.history.pushState(
null,
'',
query ? `?${query}` : window.location.pathname,
);
// pushState fires no popstate, so tell the subscribers ourselves.
for (const listener of listeners) listener();
}
export function useSearchParam(key: string): string {
return useSyncExternalStore(subscribe, () => {
const value = new URLSearchParams(window.location.search).get(key);
return value ?? '';
});
}useSearchParam is a selector subscription over the address bar — the same useSyncExternalStore shape as step 2 of the external store lesson, with the URL as the store. The getSnapshot returns a string, so identity is stable for free. One browser fact the comment preserves: pushState and replaceState fire no popstate event, so the module notifies its listeners itself after writing — forget that and the view silently disagrees with the URL. CategoryFilter and ProductGrid both call useSearchParam('category'); the grid filters its three products with the value. Drive it, press back, and watch both:
stdout | src/after.test.tsx > step 4: the category lives in the URL
render CategoryFilter (Fruit)
URL after load: ?category=Fruit
render CategoryFilter (Bakery)
URL after pick: ?category=Bakery
render CategoryFilter (Fruit)
URL after back: ?category=FruitThe page loads with the category already applied from the URL, every change writes back, and the back button restores — because the browser history is the state. On the component side, a category change re-rendered only CategoryFilter and ProductGrid; the cart badge and summary did not hear about it.
06. Step 5: a cross-page preference in a module store
Currency is read by every price on the page — and would be read on any other page in a real shop. Two components need different things of it: CurrencyPicker reads and writes the value; Price reads it to format. That is shared client state with per-component slices, so it goes in the twenty-line store, exposed through two small hooks:
import { useSyncExternalStore } from 'react';
export type Currency = 'GBP' | 'EUR';
let currency: Currency = 'GBP';
const listeners = new Set<() => void>();
export function setCurrency(next: Currency): void {
if (next === currency) return;
currency = next;
for (const listener of listeners) listener();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const getSnapshot = () => currency;
export function useCurrency(): Currency {
return useSyncExternalStore(subscribe, getSnapshot);
}No provider, no prop: any page imports the same module. The step 5 test adds two Apples, empties the log, then switches the picker to EUR. Predict which components re-render before you run it:
stdout | src/after.test.tsx > step 5: one currency switch
render CartSummary
render CurrencyPicker (EUR)
render Price 190
render Price 180
render Price 70Five components — every price and the total, which formats the derived £3.60 as €4.18 — plus the picker that owns the change. CartBadge is absent: it does not read currency, and its context value did not change, so it did not re-render. Note the division of labour: the children-prop bailout and split contexts isolate cart updates, but each Price re-renders here because it subscribes directly to the currency store — external store subscriptions notify each subscriber directly, regardless of where they sit in the component tree.
07. Step 6: document the placements
The refactor is only half the deliverable. The practice brief for this skill asks for a README table documenting each placement decision — the reasoning is the reusable part. Fill one row per value, using the four questions from the first lesson:
| Value | Home | Why |
| ------------ | ------------- | ------------------------------------------ |
| Cart lines | reducer + | Browser-owned, read at two distances, |
| | split context | changes per click; one pure reducer |
| | | owns every transition. |
| Category | URL | View state: must survive reload and |
| | | travel in shared links. |
| Currency | module store | Cross-page, read by distant slices; |
| | | selectors beat context, no provider. |
| Totals/count | derived | Computable from lines; stored copies drift |08. Check your understanding
09. Apply it
Take the lab further, one decision at a time, with a written prediction before each change. Add a quantity stepper per cart line using the setQty action and its already-tested zero-removes rule. Persist the currency choice to localStorage, reading it once when the module loads — and decide what that changes about the "Survives reload" column of your table. Then move a second filter (a maximum-price input) into the URL alongside category, reusing setParam unchanged. Finish with the full evidence the practice brief asks for: passing reducer tests, render logs before and after, and the README table with a row for every value on the page.
10. Review prompt
Without looking back: list the four values the lab placed (cart lines, category, currency, derived totals), the home of each, and the one browser behaviour that the URL module has to work around. Then explain why the badge went quiet during the currency switch while every price re-rendered.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.