useReducer

Move update logic out of event handlers into one pure function.

Builds on State.

The reading list from State had two handlers, and each one knew how to rebuild the array. Add removing, editing, "mark all read" and undo, and that knowledge spreads across five handlers in two or three components. Each one is a small, hand-written transition of the same piece of state, which is the problem from chapter 1 at a smaller scale.

useReducer moves every transition into one pure function. Event handlers stop saying how to change state and start saying what happened. That makes the logic testable without React, easy to log, and easy to hand to children as a single stable function. It's also the shape Redux, XState and most state libraries build on, so it's worth knowing well.

The problem: update logic in every handler#

Here's the reading list with a few more features. Read the handlers and notice how each one restates the shape of the data.

ReadingList.tsx (useState version)
function handleAdd(title: string) {
  setEntries([...entries, { id: nextId++, title, author: "Unknown", year: 2026, tags: [], read: false }]);
}
function handleToggle(id: number) {
  setEntries(entries.map((e) => (e.id === id ? { ...e, read: !e.read } : e)));
}
function handleRemove(id: number) {
  setEntries(entries.filter((e) => e.id !== id));
}
function handleMarkAllRead() {
  setEntries(entries.map((e) => (e.read ? e : { ...e, read: true })));
}

None of this is wrong. But to answer "what can happen to the reading list?" you have to find every setEntries call, possibly across components. To test a toggle you have to render a component and click it. And if a child needs to add a book, the parent passes onAdd; for removing, onRemove; and so on, one prop per operation.

Build it: useReducer on top of useState#

A reducer is a function (state, action) => nextState. You can build the hook in a few lines with the useState you already have:

A toy useReducer
import { useState } from "react";

function useMyReducer<S, A>(reducer: (state: S, action: A) => S, initial: S) {
  const [state, setState] = useState(initial);
  // An updater: React feeds it the pending state, so queued actions chain correctly.
  const dispatch = (action: A) => setState((s) => reducer(s, action));
  return [state, dispatch] as const;
}

type Action = { type: "incremented" } | { type: "reset" };

function counter(state: number, action: Action): number {
  switch (action.type) {
    case "incremented":
      return state + 1;
    case "reset":
      return 0;
  }
}

export default function App() {
  const [count, dispatch] = useMyReducer(counter, 0);
  return (
    <>
      <h2>{count}</h2>
      <button
        onClick={() => {
          dispatch({ type: "incremented" });
          dispatch({ type: "incremented" });
        }}
      >
        +2
      </button>{" "}
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </>
  );
}

The two dispatches add 2, not 1, because each becomes an updater function and updaters chain. Inside React the relationship runs the other way: on re-renders, useState goes through the same code path as useReducer (updateState calls updateReducer) with a built-in reducer, basicStateReducer, that either returns the value you passed or calls your updater with the previous state. In your toy from Hooks from scratch, the hook's queue held updates; here each update is an action, and the reducer is how React turns the queue into the next state.

Our toy recreates dispatch on every render. The real one doesn't.

The real useReducer#

const [state, dispatch] = useReducer(reducer, initialArg, init?);
  • reducer(state, action) must be pure and return the next state. React calls it during the next render, once per queued action.
  • initialArg is the initial state, or the argument passed to init when you provide one. useReducer(reducer, userId, createInitialState) calls createInitialState(userId) only on the first render, like a lazy useState initializer.
  • dispatch has a stable identity for the component's lifetime. You can pass it down or leave it out of dependency lists.
  • If the reducer returns the same state (by Object.is), React bails out like it does for useState.
  • dispatch doesn't change state in the running render. State is still a snapshot.
From event to new state
event handleronChangedispatch(action){ type: "toggled", id: 3 }update queueemptyreducer(state, a)pure, during rendernext stateentries[2].read = truecomponent re-rendersUI from the new stateyour codeReactyour pure function
Step 1 of 4

The user ticks a checkbox. The event handler doesn't compute anything. It describes what happened: dispatch({ type: "toggled", id: 3 }).

Typing patterns. Type actions as a discriminated union: a union of object types that share a literal type field. Inside switch (action.type), TypeScript narrows action to the matching member, so action.id is only available where it exists. Annotate the reducer's parameters and return type, and let useReducer infer the rest from the reducer. A never check in the default branch makes TypeScript complain when you add an action and forget to handle it.

type Action =
  | { type: "added"; id: number; title: string }
  | { type: "toggled"; id: number }
  | { type: "removed"; id: number };

function assertNever(x: never): never {
  throw new Error(`Unknown action: ${JSON.stringify(x)}`);
}

The reading list, part 2#

Same app as last chapter, now with every transition in readingListReducer. The component only describes what happened.

Reading list: useReducer
import { useReducer, useState } from "react";
import { books } from "guide-tools";
import { readingListReducer, type Entry } from "./readingListReducer";

let nextId = 1000;
const initialEntries: Entry[] = books.slice(0, 3).map((b) => ({ ...b, read: false }));

export default function ReadingList() {
  const [entries, dispatch] = useReducer(readingListReducer, initialEntries);
  const [title, setTitle] = useState("");
  const unread = entries.filter((e) => !e.read).length;

  return (
    <>
      <h3>Reading list ({unread} unread)</h3>
      <button onClick={() => dispatch({ type: "allMarkedRead" })}>Mark all read</button>
      <ul style={{ listStyle: "none", padding: 0 }}>
        {entries.map((e) => (
          <li key={e.id}>
            <label style={{ textDecoration: e.read ? "line-through" : "none" }}>
              <input type="checkbox" checked={e.read} onChange={() => dispatch({ type: "toggled", id: e.id })} /> {e.title}
            </label>{" "}
            <button onClick={() => dispatch({ type: "removed", id: e.id })}>✕</button>
          </li>
        ))}
      </ul>
      <form
        onSubmit={(ev) => {
          ev.preventDefault();
          if (!title.trim()) return;
          // Ids are generated here, not in the reducer, so the reducer stays pure.
          dispatch({ type: "added", id: nextId++, title: title.trim() });
          setTitle("");
        }}
      >
        <input aria-label="New book" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Add a book" />
        <button>Add</button>
      </form>
    </>
  );
}

The local title stays in useState. Not everything has to go through the reducer. Use the reducer for the state whose transitions matter; keep a form draft local.

Actions describe events, not setters#

Name actions after what happened in the app ("added", "toggled", "checkoutStarted"), not after the state change you want ("setEntries", "setRead"). An action like { type: "setEntries", entries } just moves the update logic back into the handler. One user event should usually be one action, even if it changes several fields; the reducer decides what that means. It also makes a log of actions read like a story of what the user did, which is exactly what Redux DevTools shows you (Redux Toolkit).

Reducers must be pure#

The reducer runs during render, so it follows the same rules as render (Components and props): same state and action in, same state out, nothing outside touched. In StrictMode React calls it twice in development to catch violations. That rules out:

  • Fetching, logging to a server, writing to localStorage. Do those in the event handler or an effect.
  • Date.now(), Math.random() or crypto.randomUUID(). Generate the value in the handler and put it in the action, as the form above does with id.
  • Mutating state. Return a new value.

Purity is also what makes reducers so easy to test. No rendering, no clicks:

const before = [{ ...books[0], read: false }];
const after = readingListReducer(before, { type: "toggled", id: 1 });
expect(after[0].read).toBe(true);
expect(before[0].read).toBe(false); // untouched

Immer for reducers#

Spreads get long once state is nested. Immer's produce, called with just a recipe, returns a function with the reducer signature (state, action) => nextState. Your recipe receives a draft you're allowed to mutate, and Immer builds the immutable result.

A reducer written with Immer
import { useReducer } from "react";
import { produce } from "immer";
import { books } from "guide-tools";

type Entry = (typeof books)[number] & { read: boolean; notes: string[] };
type Action = { type: "toggled"; id: number } | { type: "noteAdded"; id: number; text: string };

const reducer = produce((draft: Entry[], action: Action) => {
  const entry = draft.find((e) => e.id === action.id);
  if (!entry) return;
  switch (action.type) {
    case "toggled":
      entry.read = !entry.read; // a "mutation" on the draft
      break;
    case "noteAdded":
      entry.notes.push(action.text);
      break;
  }
});

const initial: Entry[] = books.slice(0, 2).map((b) => ({ ...b, read: false, notes: [] }));

export default function App() {
  const [entries, dispatch] = useReducer(reducer, initial);
  return (
    <ul>
      {entries.map((e) => (
        <li key={e.id}>
          <label>
            <input type="checkbox" checked={e.read} onChange={() => dispatch({ type: "toggled", id: e.id })} /> {e.title}
          </label>{" "}
          <button onClick={() => dispatch({ type: "noteAdded", id: e.id, text: `note ${e.notes.length + 1}` })}>Add note</button>
          {e.notes.length > 0 && <small> ({e.notes.join(", ")})</small>}
        </li>
      ))}
    </ul>
  );
}

With Immer, a recipe either mutates the draft and returns nothing, or returns a whole new state. Don't do both in one branch. Immer also freezes the state it produces by default (its autoFreeze setting, on in development and production), so accidental mutation outside a recipe throws in strict-mode code, which includes every ES module, instead of silently doing nothing. The cost is a proxy layer and a dependency; for flat state, plain spreads are just as clear. A use-immer package wraps this into useImmerReducer if you prefer a hook.

When to prefer useReducer over useState#

They're interchangeable in power: anything one can do, the other can. The choice is about how the code reads. React's own docs frame it as a comparison, and that's how to answer in an interview:

useStateuseReducer
Code sizeLess for simple valuesMore up front (actions, a switch)
ReadabilityGreat for independent valuesBetter when updates are complex or related
Where logic livesIn each handlerIn one function, separate from the UI
TestingNeeds a renderReducer is a plain function
DebuggingFind the setter callLog every action and state
Passing downOne callback per operationOne stable dispatch

Reach for a reducer when several pieces of state change together, when the next state depends on several current values, when you have many kinds of updates to the same data, or when children need to trigger many different updates. dispatch pairs especially well with context: provide it once and any descendant can send any action, which Context does with the reading list.

Don't reach for one for a single boolean or an input's text. A reducer there is ceremony.

Pitfalls#

Check your understanding#

Build itWrite the reading list reducer

Implement readingListReducer so the app works and the checks pass. It must handle added, toggled, removed and allMarkedRead, and it must never mutate the state it receives (the checks freeze it).

export type Entry = { id: number; title: string; read: boolean };

export type Action =
  | { type: "added"; id: number; title: string }
  | { type: "toggled"; id: number }
  | { type: "removed"; id: number }
  | { type: "allMarkedRead" };

export function readingListReducer(entries: Entry[], action: Action): Entry[] {
  // TODO
  return entries;
}
PredictDispatch, then log

count is 0. What does the console show after one click, and what does the screen show?

const [state, dispatch] = useReducer(reducer, { count: 0 });

function handleClick() {
  dispatch({ type: "incremented" });
  dispatch({ type: "incremented" });
  console.log(state.count);
}
Quick checkPick the tool

Which situation is the best fit for useReducer?

Explain it out louduseState or useReducer?

An interviewer asks: "When would you use useReducer instead of useState? Is one more powerful?"

Interview angle

Say it in 30 seconds

useReducer moves state transitions out of event handlers into one pure function: reducer(state, action) returns the next state. Handlers dispatch actions that describe what happened, like toggled or added, and React queues them and runs the reducer during the next render, chaining actions like updater functions. dispatch is stable, so it's easy to pass down or put in context. It's not more powerful than useState, which is itself a reducer under the hood; it's better organized when there are many related updates. Reducers must be pure, and Immer's produce makes nested updates readable.

What is a reducer, and how does useReducer work?

basic

When do you choose useReducer over useState?

intermediate

What can't you do inside a reducer, and where does that work go instead?

intermediate

How should you design actions?

senior

How does Immer help with reducers, and what does it cost?

senior

Recap#

  • A reducer is a pure function (state, action) => nextState. Handlers dispatch actions that describe what happened; the reducer decides what that means for state.
  • useReducer queues actions like useState queues updates and runs the reducer during the next render, chaining queued actions. dispatch is stable, and state is still a snapshot.
  • Type actions as a discriminated union and add a never check so missing cases fail to compile.
  • Keep reducers pure: no effects, no randomness, no mutation. Put generated values in the action. Use Immer's produce when nested updates get noisy.
  • Prefer a reducer for many related updates, many update sites or many children; prefer useState for simple, independent values.

Sources#