Lesson 11 of 37State
useReducer
Move growing state logic into a pure, typed reducer, handle nested state with Immer, scale it into a feature, and model flows as state machines.
As a component grows, its event handlers fill up with setX calls: add a todo here, toggle one there, clear the done ones somewhere else. The logic for "how does state change?" ends up scattered across five handlers. useReducer pulls it all into one pure function you can read top to bottom and test in isolation. It is also the exact model behind Redux, so learning it pays off twice.
From scattered setters to one function
Here is the idea before the hook. A reducer is a function that takes the current state and an action (an object describing what happened) and returns the next state:
(state, action) => newStateIt is called a reducer because it has the same shape as the callback you pass to Array.prototype.reduce. In fact you can replay a list of actions with reduce. Run this:
Press Run (⌘ Enter) to see what happens.Event handlers stop saying how to change state and only say what happened: "the user added 5". The reducer decides what that means.
The hook
const [state, dispatch] = useReducer(reducer, initialState);stateis the current state, like the first value fromuseState.dispatch(action)sends an action. React callsreducer(state, action), stores the result, and re-renders.
The button's onClick runs.
The same rules as state apply: the reducer must not mutate state (return a new object), and it must be pure (no API calls, no random numbers, no timers). React may call it more than once in development to catch impurity.
dispatch({ type: 'incremented' }) inside a click handler, what is state.count?Actions as discriminated unions
In TypeScript, model actions as a discriminated union: a union of object types that all share a literal type field. Inside switch (action.type), TypeScript narrows the action, so action.id is only available in the cases whose type has an id.
type Todo = { id: number; text: string; done: boolean };
type TodoAction =
| { type: "added"; id: number; text: string }
| { type: "toggled"; id: number }
| { type: "deleted"; id: number }
| { type: "clearedDone" };
function todoReducer(todos: Todo[], action: TodoAction): Todo[] {
switch (action.type) {
case "added":
return [...todos, { id: action.id, text: action.text, done: false }];
case "toggled":
return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "deleted":
return todos.filter((t) => t.id !== action.id);
case "clearedDone":
return todos.filter((t) => !t.done);
default: {
const unreachable: never = action; // compile error if a case is missing
return unreachable;
}
}
}The never trick in default is an exhaustiveness check: if someone adds { type: "renamed" } to the union and forgets a case, TypeScript reports an error at that line. Action names in the past tense ("added", "toggled") describe what the user did, which keeps reducers readable.
clearedDone case, what happens if you write action.id?A todo app with a reducer
Here is that reducer driving a real UI. Notice how small the event handlers are: each one dispatches a single action.
The id is created in the handler (nextId++), not in the reducer, because generating ids is a side effect and reducers must be pure. The draft text stays in useState: you can mix both hooks freely.
Using todoReducer from above, what is logged?
let s: Todo[] = [];
s = todoReducer(s, { type: "added", id: 1, text: "a" });
s = todoReducer(s, { type: "added", id: 2, text: "b" });
s = todoReducer(s, { type: "toggled", id: 1 });
s = todoReducer(s, { type: "clearedDone" });
console.log(s.map((t) => t.text).join(","));Testing reducers
Because a reducer is a pure function with no React in it, testing it is just calling it. No rendering, no clicking, no mocking. This is one of the strongest arguments for reducers in larger apps.
Press Run (⌘ Enter) to see what happens.In a real project these would be expect assertions in Vitest or Jest, which the testing React lesson covers.
Lazy initial state and bailing out
Two small details of useReducer show up in code review.
Lazy initialisation. If building the initial state is expensive (parsing a saved draft, building a big lookup), pass the raw input as the second argument and an init function as the third. React calls init(arg) once, on mount.
// Runs createInitialState on every render, then throws the result away after the first
const [state, dispatch] = useReducer(reducer, createInitialState(savedDraft));
// Runs it once
const [state, dispatch] = useReducer(reducer, savedDraft, createInitialState);This is the same idea as passing a function to useState, which you saw in the useState lesson.
Bailing out. If the reducer returns the exact same state object it was given, React compares with Object.is, sees nothing changed, and skips re-rendering the children. So for an action that changes nothing (toggling an id that does not exist, a filter set to its current value), return state itself rather than a copy. A copy is a new object, so React has to treat it as a change. React may still call your component one extra time before it bails out, so do not rely on this to prevent side effects; render is supposed to be pure anyway.
case "filterChanged":
if (action.filter === state.filter) return state; // same object: React can skip the update
return { ...state, filter: action.filter };localStorage only once, when the component mounts?Immer and useImmerReducer
Reducers that only touch flat state stay short. Real state nests: a board with columns with cards with comments. Updating one comment immutably means copying every level on the path to it.
Press Run (⌘ Enter) to see what happens.The output shows structural sharing: only the objects on the path to the change are new, and everything else is the same object as before. That is what makes memo and bail-outs work, and it is why you cannot simply deep-clone the whole state.
Immer gives you the same result with code that looks like mutation. You change a draft, a proxy that records what you did, and Immer builds the new state with structural sharing for you. The use-immer package wraps it in a hook, useImmerReducer, whose reducer receives the draft:
import { useImmerReducer } from "use-immer";
type BoardAction =
| { type: "cardDone"; columnId: string; cardId: number }
| { type: "cardAdded"; columnId: string; card: Card }
| { type: "reset"; board: Board };
function boardReducer(draft: Board, action: BoardAction) {
switch (action.type) {
case "cardDone": {
const card = draft.columns.find((c) => c.id === action.columnId)?.cards.find((c) => c.id === action.cardId);
if (card) card.done = true; // looks like mutation, produces a new Board
break;
}
case "cardAdded":
draft.columns.find((c) => c.id === action.columnId)?.cards.push(action.card);
break;
case "reset":
return action.board; // returning a value replaces the state
}
}
export function useBoard(initial: Board) {
return useImmerReducer(boardReducer, initial);
}The rules that catch people:
- Mutate the draft or return a new value, never both. Changing
draftand also returning a different object makes Immer throw. Returning nothing (undefined) means "use the draft". - Only the draft is safe to mutate. Immer freezes the state it produces by default, so mutating it outside a producer fails loudly instead of silently corrupting state.
- Drafts are temporary. Do not store a draft in a variable outside the reducer or pass it to
setTimeout; it is revoked when the reducer returns. - Cost. It is one more dependency, and proxies make each update a little slower than hand-written spreads. That rarely matters for UI state; it can for hot loops over thousands of items.
Use Immer when your state is genuinely nested and the spreads hide the intent. For flat state, plain spreads are clearer. You will meet Immer again inside Redux Toolkit in the state management at scale lesson, where createSlice uses it by default.
useImmerReducer reducer, a case does draft.items.push(action.item); return { ...draft };. What happens?A reducer and context for one feature
The context lesson shows how to put a reducer's state and dispatch into two contexts so any component can use them, and why splitting them avoids re-renders. Here is how that looks as a feature module in a real codebase, organised so the rest of the app never sees the plumbing.
- features/
- cart/
- cart-reducer.tsstate type, action union, pure reducer
- cart-reducer.test.tsunit tests, no React
- CartProvider.tsxuseReducer + two contexts
- use-cart.tsuseCart() and useCartActions()
- CartSummary.tsxreads with useCart()
- AddToCartButton.tsxwrites with useCartActions()
The provider and hooks are the only public surface. Components never import the context objects or build action objects by hand:
import { useContext, useMemo } from "react";
import { CartStateContext, CartDispatchContext } from "./CartProvider";
export function useCart() {
const state = useContext(CartStateContext);
if (!state) throw new Error("useCart must be used inside <CartProvider>");
return state;
}
export function useCartActions() {
const dispatch = useContext(CartDispatchContext);
if (!dispatch) throw new Error("useCartActions must be used inside <CartProvider>");
return useMemo(
() => ({
addItem: (product: Product) => dispatch({ type: "itemAdded", product }),
removeItem: (id: string) => dispatch({ type: "itemRemoved", id }),
applyCoupon: async (code: string) => {
const coupon = await api.checkCoupon(code); // async work stays out of the reducer
dispatch(coupon ? { type: "couponApplied", coupon } : { type: "couponRejected", code });
},
}),
[dispatch],
);
}Why teams structure it this way:
- Named actions hide the action shape.
addItem(product)reads better at the call site, and you can rename an action type without touching twenty components. - Async lives in the actions hook, not the reducer. The reducer stays pure and only ever sees the results:
couponAppliedorcouponRejected. That also makes every outcome an explicit, testable action. - The reducer file has no React imports. It is tested with plain function calls, as you saw above.
- The provider wraps only what needs it. Put
<CartProvider>around the shop routes, not the whole app, so unrelated screens never re-render when the cart changes.
When the feature's state is needed across the whole app, changes very often, or needs devtools and middleware, this is the point where teams move to a store such as Zustand or Redux Toolkit. The reducer you wrote moves across almost unchanged.
State machines for multi-step flows
Multi-step flows are where reducer bugs hide. A checkout has a details step, a shipping step, a payment step, a "submitting" wait and a result. Track that with step: number plus isSubmitting and error flags and you can reach states nobody designed: the Back button working while the payment is in flight, Pay clicked twice and charged twice, an error showing on the details step.
A state machine fixes this by making two things explicit: a finite list of states the flow can be in, and for each state, which events it accepts and where each one leads. Any event not listed for the current state is simply ignored.
Each step is a state. In each one, only the listed events do anything: there is no PAY arrow out of details, so paying from step one is impossible.
You do not need a library to get most of the benefit. A reducer that switches on the current state first, then on the event, is a state machine. Click Pay several times quickly, and try Back while it submits.
Every button is always clickable, and the machine decides what each click means. Back during submitting does nothing, and a burst of Pay clicks sends one request, because only the payment state accepts PAY and the pay handler checks the current state before starting a request. (payCalls is a module variable only to keep the demo short; in real code the request would start from an effect or an action that watches for the submitting state.)
For larger flows, XState is the standard library. It adds things a hand-written reducer makes painful: nested and parallel states, delayed transitions (time out after 30 seconds), invoking promises as part of a state, and a visual editor. A sketch of the same checkout in XState v5 (check the XState docs for the full API):
import { setup, fromPromise } from "xstate";
export const checkoutMachine = setup({
actors: {
pay: fromPromise(async ({ input }: { input: { total: number } }) => chargeCard(input.total)),
},
}).createMachine({
id: "checkout",
initial: "details",
states: {
details: { on: { NEXT: "shipping" } },
shipping: { on: { NEXT: "payment", BACK: "details" } },
payment: { on: { PAY: "submitting", BACK: "shipping" } },
submitting: {
invoke: { src: "pay", input: { total: 42 }, onDone: "done", onError: "failed" },
},
failed: { on: { RETRY: "payment" } },
done: { type: "final" },
},
});
// in a component, with @xstate/react:
// const [snapshot, send] = useMachine(checkoutMachine);
// snapshot.matches("payment") && <button onClick={() => send({ type: "PAY" })}>Pay</button>Reach for a machine when a flow has more than a few steps, when "what can the user do right now?" is a frequent bug, or when product and design need to agree on every path. For a toggle or a simple form, it is overkill.
Using the checkout reducer above, what is logged?
let s: State = { status: "payment" };
s = checkout(s, { type: "PAY" });
s = checkout(s, { type: "PAY" });
s = checkout(s, { type: "BACK" });
s = checkout(s, { type: "FAILED", message: "Card declined" });
s = checkout(s, { type: "NEXT" });
console.log(s.status);useState or useReducer?
useState | useReducer | |
|---|---|---|
| Best for | Independent, simple values (a boolean, a string) | Related values that change together, many kinds of update |
| Update logic lives | In each event handler | In one reducer function |
| Testing | Through the component | Call the reducer directly |
| Code size | Smaller | More upfront (types, switch), less as it grows |
There is no wrong answer. A good rule: start with useState, and switch to a reducer when several handlers update the same state in different ways or when you find a bug and cannot tell which handler caused it.
Pick the hook that fits best.
Todo reducer
Write a pure reducer todoReducer(todos, action) that returns the next list of todos. A todo is { id, text, done }. Handle four actions:
| action | effect |
|---|---|
{ type: "added", id, text } | append { id, text, done: false } |
{ type: "toggled", id } | flip done on the todo with that id |
{ type: "deleted", id } | remove the todo with that id |
{ type: "clearedDone" } | remove every todo that is done |
An action that refers to an id that does not exist leaves the list unchanged. Never mutate the input array or its todos.
todoReducer([], { type: "added", id: 1, text: "Write tests" })
→ [{ id: 1, text: "Write tests", done: false }]Todo app with useReducer
Build a todo app whose list state lives in useReducer.
- A form with
<input type="text" aria-label="New todo">and a submit buttonAdd. Submitting adds the trimmed text as a new todo and clears the input. Empty or whitespace-only text adds nothing. - Each todo is an
<li>containing a checkbox (checked when done), the text, and aDeletebutton. - Below the list,
<p className="left">N left</p>counts the todos that are not done.
The reducer is started for you. Generate ids in the event handler, not in the reducer.
- reducer
- A pure function
(state, action) => newStatethat holds all the update logic in one place. - action
- A plain object describing what happened, usually
{ type: "added", ...data }. - dispatch
- The function from
useReducerthat sends an action; React runs the reducer and re-renders. - discriminated union
- A union of object types sharing a literal field (like
type) that TypeScript uses to narrow. - exhaustiveness check
- Assigning the leftover value to
neverindefaultso a missing case is a compile error. - structural sharing
- An immutable update that creates new objects only along the path to the change and reuses everything else.
- Immer
- A library that turns mutations on a temporary draft into a new immutable state.
useImmerReducercomes fromuse-immer. - state machine
- A finite set of states plus the events each state accepts; events not listed for the current state are ignored.
- lazy initialiser
- The third argument to
useReducer, called once on mount to build the initial state.