Skip to content
ClapelloNotes by Barath
ReactCh 15 · 3/6
Core5 min readUpdated

React / 84

useReducer: state changes as actions

TL;DR

Move every way your state can change into one pure function. Handlers dispatch plain action objects that say what happened, and the reducer returns the next state.

The shape

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer: a function (state, action) => nextState. It's the only place the state changes.
  • dispatch: what you call from handlers, with an action, a plain object describing what happened: dispatch({ type: "deleted", id: 3 }).
  • React calls your reducer with the current state and the action, stores what it returns, and re-renders.

1 · event handler

The user ticks a todo

dispatch({ type: "toggled", id: 2 })
action

2 · reducer (pure)

todosReducer(todos, action)

returns a new array with todo 2 flipped
next state

3 · re-render

React stores it and re-renders

the list shows todo 2 as done
Handlers say what happened. The reducer alone decides how the state changes, so every update has one home you can read, log and test.

Example: a todo list

todosReducer.js
export function todosReducer(todos, action) {
  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);
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
TodoApp.jsx
import { useReducer } from "react";
import { todosReducer } from "./todosReducer";
 
let nextId = 3;
const initialTodos = [
  { id: 1, text: "Buy paneer", done: true },
  { id: 2, text: "Book a table", done: false },
];
 
export default function TodoApp() {
  const [todos, dispatch] = useReducer(todosReducer, initialTodos);
 
  return (
    <>
      <button onClick={() => dispatch({ type: "added", id: nextId++, text: "New todo" })}>Add</button>
      <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 })}>Delete</button>
          </li>
        ))}
      </ul>
    </>
  );
}

Every handler is now one line, and the reducer reads like a list of everything that can happen. Name action types after what happened ("added", "toggled"), not what to do ("setTodos").

Every change is an action

Try it

action log · newest first

  1. Tick, delete or add a todo.
Every click dispatches one plain object. The reducer is the only code that changes the list, so the log explains every state you see.

Keep the reducer pure

React calls your reducer during rendering, so it follows the same rules as a component:

  • No side effects. No fetching, timers or writing to localStorage. Do those in handlers or effects.
  • No randomness. Date.now() or Math.random() gives a different result each call. Create ids in the handler and put them in the action, as nextId++ does above.
  • No mutation. todos.push(item); return todos; returns the same array, so React sees no change and may skip the re-render. Return a new array or object, exactly as with useState.

In development, StrictMode calls your reducer twice with the same arguments to catch impure ones.

useState or useReducer?

useStateuseReducer
Best forA few independent valuesMany ways to change the same state
Update logic livesIn each handlerIn one reducer function
DebuggingFind which handler did itLog the action at the top of the reducer
TestingRender the componentCall todosReducer(state, action) in a plain test
Code sizeSmallerA bit more up front

Both are fine. Start with useState, and switch when the handlers start to look alike or a bug makes you hunt through all of them. You can mix the two in one component.

How it relates to Redux

If this looks like the Redux loop, it is the same idea: actions, a pure reducer, one-way flow. The differences are scope and tooling. useReducer state belongs to one component and its children; Redux is one store for the whole app, with DevTools, middleware and createSlice. Many apps use useReducer plus Context before they ever need Redux.

Two details seniors use

  • dispatch never changes. It's the same function on every render, so you can pass it to children or leave it out of effect dependency arrays without problems.
  • Lazy initial state. useReducer(reducer, userId, createInitialState) calls createInitialState(userId) once on mount, instead of rebuilding an expensive starting state on every render.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.