Skip to content

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.

21 min read0/7 questions

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) => newState

It 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:

TypeScript
type Action = { type: "added"; amount: number } | { type: "reset" }; function counterReducer(state: number, action: Action): number { switch (action.type) { case "added": return state + action.amount; case "reset": return 0; }} const actions: Action[] = [ { type: "added", amount: 5 }, { type: "added", amount: 3 }, { type: "reset" }, { type: "added", amount: 2 },]; console.log(actions.reduce(counterReducer, 0));
Output
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);
  • state is the current state, like the first value from useState.
  • dispatch(action) sends an action. React calls reducer(state, action), stores the result, and re-renders.
React
import { useReducer } from "react"; type State = { count: number; step: number };type Action = { type: "incremented" } | { type: "decremented" } | { type: "stepChanged"; step: number } | { type: "reset" }; function reducer(state: State, action: Action): State { switch (action.type) { case "incremented": return { ...state, count: state.count + state.step }; case "decremented": return { ...state, count: state.count - state.step }; case "stepChanged": return { ...state, step: action.step }; case "reset": return { count: 0, step: 1 }; }} export default function App() { const [state, dispatch] = useReducer(reducer, { count: 0, step: 1 }); return ( <div> <p>Count: {state.count}</p> <label> Step{" "} <input type="number" aria-label="Step" value={state.step} onChange={(e) => dispatch({ type: "stepChanged", step: Number(e.target.value) })} /> </label> <div style={{ display: "flex", gap: 6, marginTop: 6 }}> <button onClick={() => dispatch({ type: "decremented" })}>-</button> <button onClick={() => dispatch({ type: "incremented" })}>+</button> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> </div> );}
One dispatch, start to finish
UserComponentReactReducerclicks +dispatch({ type: 'incremented' })reducer(state, action){ count: 1, step: 1 }re-render with new state

The button's onClick runs.

1/5

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.

Quick check
Right after dispatch({ type: 'incremented' }) inside a click handler, what is state.count?
Need a nudge? A hint rules out a wrong answer.

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.

Quick check
In the clearedDone case, what happens if you write action.id?
Need a nudge? A hint rules out a wrong answer.

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.

React
import { useReducer, useState } from "react"; 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); }} let nextId = 3; export default function App() { const [todos, dispatch] = useReducer(todoReducer, [ { id: 1, text: "Read about reducers", done: true }, { id: 2, text: "Write one", done: false }, ]); const [draft, setDraft] = useState(""); return ( <div> <form onSubmit={(e) => { e.preventDefault(); if (!draft.trim()) return; dispatch({ type: "added", id: nextId++, text: draft.trim() }); setDraft(""); }} > <input aria-label="New todo" value={draft} onChange={(e) => setDraft(e.target.value)} /> <button type="submit">Add</button> </form> <ul> {todos.map((t) => ( <li key={t.id}> <input type="checkbox" checked={t.done} onChange={() => dispatch({ type: "toggled", id: t.id })} />{" "} {t.text} <button onClick={() => dispatch({ type: "deleted", id: t.id })}>x</button> </li> ))} </ul> <button onClick={() => dispatch({ type: "clearedDone" })}>Clear done</button> </div> );}

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.

Predict the outputTypeScript

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(","));
Need a nudge? Hints walk you through it.

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.

TypeScript
type Todo = { id: number; text: string; done: boolean };type TodoAction = { type: "added"; id: number; text: string } | { type: "toggled"; id: number }; 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)); }} const start: Todo[] = [{ id: 1, text: "a", done: false }];const next = todoReducer(start, { type: "toggled", id: 1 }); console.log("toggles done:", next[0].done === true);console.log("does not mutate:", start[0].done === false);console.log("new array:", next !== start);
Output
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 };
Quick check
Which call parses localStorage only once, when the component mounts?
Need a nudge? A hint rules out a wrong answer.

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.

TypeScript
type Card = { id: number; title: string; done: boolean };type Column = { id: string; cards: Card[] };type Board = { title: string; columns: Column[] }; const board: Board = { title: "Sprint 12", columns: [ { id: "todo", cards: [{ id: 1, title: "Login page", done: false }] }, { id: "doing", cards: [{ id: 2, title: "Search API", done: false }, { id: 3, title: "Rate limits", done: false }] }, ],}; // Mark card 3 done in column "doing": copy board, columns, that column, its cards, that cardfunction cardDone(state: Board, columnId: string, cardId: number): Board { return { ...state, columns: state.columns.map((col) => col.id !== columnId ? col : { ...col, cards: col.cards.map((c) => (c.id !== cardId ? c : { ...c, done: true })) }, ), };} const next = cardDone(board, "doing", 3);console.log("card 3 done:", next.columns[1].cards[1].done);console.log("original untouched:", board.columns[1].cards[1].done === false);console.log("todo column reused:", next.columns[0] === board.columns[0]);console.log("card 2 reused:", next.columns[1].cards[0] === board.columns[1].cards[0]);
Output
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:

features/board/useBoard.ts
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 draft and 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.

Quick check
In a useImmerReducer reducer, a case does draft.items.push(action.item); return { ...draft };. What happens?
Need a nudge? A hint rules out a wrong answer.

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.

A self-contained cart feature
  • 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:

features/cart/use-cart.ts
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: couponApplied or couponRejected. 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.

Checkout as a state machine
detailsdetailsshippingshippingpaymentpaymentsubmitting: waiting for the serversubmittingwaiting for the serverdonedonefailed: keeps the errorfailedkeeps the errorNEXTNEXTBACKBACKPAYSUCCEEDEDFAILEDRETRY

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.

1/4

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.

React
import { useReducer } from "react"; type State = | { status: "details" } | { status: "shipping" } | { status: "payment" } | { status: "submitting"; attempt: number } | { status: "done"; orderId: string } | { status: "failed"; message: string; attempt: number }; type Event = | { type: "NEXT" } | { type: "BACK" } | { type: "PAY" } | { type: "SUCCEEDED"; orderId: string } | { type: "FAILED"; message: string } | { type: "RETRY" }; function checkout(state: State, event: Event): State { switch (state.status) { case "details": return event.type === "NEXT" ? { status: "shipping" } : state; case "shipping": if (event.type === "NEXT") return { status: "payment" }; if (event.type === "BACK") return { status: "details" }; return state; case "payment": if (event.type === "PAY") return { status: "submitting", attempt: 1 }; if (event.type === "BACK") return { status: "shipping" }; return state; case "submitting": if (event.type === "SUCCEEDED") return { status: "done", orderId: event.orderId }; if (event.type === "FAILED") return { status: "failed", message: event.message, attempt: state.attempt }; return state; // PAY, BACK and NEXT are ignored while submitting case "failed": return event.type === "RETRY" ? { status: "payment" } : state; case "done": return state; }} let payCalls = 0; export default function App() { const [state, send] = useReducer(checkout, { status: "details" }); function pay() { if (state.status !== "payment") return; // the UI asks the machine, not a flag send({ type: "PAY" }); payCalls += 1; const call = payCalls; setTimeout(() => { send(call % 2 === 1 ? { type: "FAILED", message: "Card declined" } : { type: "SUCCEEDED", orderId: "A-" + (1000 + call) }); }, 700); } return ( <div style={{ display: "grid", gap: 8, maxWidth: 340 }}> <p> State: <strong>{state.status}</strong> {state.status === "failed" && ` (${state.message})`} {state.status === "done" && ` (order ${state.orderId})`} </p> <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}> <button onClick={() => send({ type: "BACK" })}>Back</button> <button onClick={() => send({ type: "NEXT" })}>Next</button> <button onClick={pay}>Pay</button> <button onClick={() => send({ type: "RETRY" })}>Retry</button> </div> <small>Payment requests sent: {payCalls}. The fake card is declined every other attempt.</small> </div> );}

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):

features/checkout/checkout-machine.ts
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.

Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

useState or useReducer?

useStateuseReducer
Best forIndependent, simple values (a boolean, a string)Related values that change together, many kinds of update
Update logic livesIn each event handlerIn one reducer function
TestingThrough the componentCall the reducer directly
Code sizeSmallerMore 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.

Match the pairs0/4 matched

Pick the hook that fits best.

Choose an item, then its match on the other side.
ChallengeMedium

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:

actioneffect
{ 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 }]
TypeScript
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 on action.type and return a new array for each case return todos;}
ChallengeMedium

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 button Add. 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 a Delete button.
  • 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.

React
import { useReducer, useState } from "react"; type Todo = { id: number; text: string; done: boolean };type Action = | { type: "added"; id: number; text: string } | { type: "toggled"; id: number } | { type: "deleted"; id: number }; function reducer(todos: Todo[], action: Action): Todo[] { // handle added, toggled and deleted return todos;} export default function App() { const [todos, dispatch] = useReducer(reducer, []); const [draft, setDraft] = useState(""); return ( <div> <form> <input type="text" aria-label="New todo" /> <button type="submit">Add</button> </form> <ul></ul> <p className="left">0 left</p> </div> );}
Key terms
reducer
A pure function (state, action) => newState that holds all the update logic in one place.
action
A plain object describing what happened, usually { type: "added", ...data }.
dispatch
The function from useReducer that 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 never in default so 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. useImmerReducer comes from use-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.