Skip to content
jshacks.dev
Frameworks

Manage complex state with useReducer

Move state updates for a React component into a reducer function with useReducer, so every transition is named and lives in one place.

1 min read
Summarize in AI

When several handlers each call a different setter and the pieces must change together, the logic scatters across the component. A reducer gathers every transition into one function.

src/Todos.jsxJSX
import { useReducer } from 'react';

function reducer(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 'removed':
      return todos.filter((t) => t.id !== action.id);
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}

export function Todos() {
  const [todos, dispatch] = useReducer(reducer, []);

  return (
    <div>
      <button onClick={() => dispatch({ type: 'added', id: 1, text: 'Write snippet' })}>
        Add
      </button>
      <ul>
        {todos.map((t) => (
          <li key={t.id} onClick={() => dispatch({ type: 'toggled', id: t.id })}>
            {t.done ? '✓ ' : ''}{t.text}
          </li>
        ))}
      </ul>
    </div>
  );
}
Text
(click Add)       -> Write snippet
(click the item)  -> ✓ Write snippet

dispatch sends an action, React calls reducer(currentState, action) and renders with what it returns. The reducer must be pure and must return a new array rather than mutate, which is what the spread and map do. See useReducer.

For one or two independent values useState is shorter. Reach for a reducer when updates depend on several fields or when you want the transitions to be easy to test.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.