Skip to content

Writing Reducers Well

The Course
•
20 min study

A reducer is a small function, but it has strict rules. Breaking them causes bugs that are hard to spot, because the code looks reasonable.

The rules

  1. Return the next state; never change the current one. The same rule as state on Day 4 of React Beginner: new arrays and objects, never push, never assignment to a field.
  2. Be pure. The same state and action always give the same result. No Date.now(), Math.random(), network calls or logging in a reducer.
  3. Handle every case, and throw on unknown actions. A misspelled action type should fail loudly, not silently do nothing.
  4. Name actions after what happened, in the past tense: card_moved, not setColumn. One user action is one action, even if it changes several things.

Find the bugs

This board uses a reducer with two bugs in it. Try to move a card, then remove one. Before reading the hints, find each bug in boardReducer.js and say which rule it breaks.

Two bugs React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function AddCard({ onAdd }) { const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim(), 15); setTitle(""); } return ( <form className="toolbar" onSubmit={handleSubmit}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> </form> ); } import { useReducer } from "react"; import AddCard from "./AddCard.jsx"; import Board from "./Board.jsx"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, dispatch] = useReducer(boardReducer, starterCards); return ( <main> <h1>Study Board</h1> <AddCard onAdd={(title, minutes) => dispatch({ type: "card_added", id: Date.now(), title, minutes })} /> <Board cards={cards} onMove={(id, column) => dispatch({ type: "card_moved", id, column })} onRemove={(id) => dispatch({ type: "card_removed", id })} /> </main> ); } import { columns } from "./data.js"; export default function Board({ cards, onMove, onRemove }) { return ( <div className="board"> {columns.map((column, index) => { const inColumn = cards.filter((card) => card.column === column.id); const next = columns[index + 1]; return ( <section key={column.id} className="column"> <h2> {column.title} <span className="count">({inColumn.length})</span> </h2> <ul className="cards"> {inColumn.map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => onMove(card.id, next.id)} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => onRemove(card.id)} aria-label={`Remove ${card.title}`}>×</button> </li> ))} </ul> </section> ); })} </div> ); } export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": { const card = cards.find((c) => c.id === action.id); card.column = action.column; return cards; } case "card_removed": cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Bug 1: moving does nothing

card_moved finds the card, sets card.column on the existing object, and returns the same array. React compares the old and new state, sees the same array, and skips the re-render. This breaks rule 1:

JavaScript
case "card_moved": {
  const card = cards.find((c) => c.id === action.id);
  card.column = action.column;
  return cards;
}

Fix it with a map that returns a new object for the moved card.

Bug 2: removing throws Unknown action

The console says Unknown action: card_removed, which seems impossible: there is a case for it. Look closely: cards.filter(...) has no return. Its result is thrown away, and the switch falls through to the next case, default, which throws:

JavaScript
case "card_removed":
  cards.filter((card) => card.id !== action.id);
default:
  throw new Error(`Unknown action: ${action.type}`);

Every case must return. This is the most common reducer bug. Some teams wrap each case in braces and add a lint rule that flags fall-through.

Show the fixed cases
JavaScript
case "card_moved":
  return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card));
case "card_removed":
  return cards.filter((card) => card.id !== action.id);

Why throw on unknown actions?

Remove the default case and dispatch { type: "card_remvoed", id }, with the typo. The reducer returns undefined, and the next render crashes in Board with Cannot read properties of undefined, a long way from the real mistake. With the throw, the console names the misspelled action straight away.

StrictMode calls reducers twice

In development, <StrictMode> calls your reducer twice for each action and keeps one result. A pure reducer gives the same answer both times, so you never notice. An impure one, say one that pushes to an array, shows the card twice. That's on purpose: it surfaces impurity early.

Exercise

Spot the rule

Which rule does each of these break?

  1. case "card_added": return [...cards, { id: Date.now(), title: action.title }];
  2. case "card_moved": cards[0].column = "done"; return [...cards];
  3. dispatch({ type: "set_cards", cards: newCards }) from every handler.
Hint 1: the idea

A reducer must be repeatable and leave its inputs unchanged. Actions should describe what happened so the reducer can enforce the rule.

Hint 2: a first step

Look for time or randomness, for changes to the existing state, and for actions that describe a result instead of an event.

Show one solution
  1. Purity. Date.now() belongs in the handler, and the id goes in the action.
  2. Never change state. The spread makes a new array, but the first card object is still the old one, changed in place. Anything holding the old state now sees the change too.
  3. Name what happened. set_cards moves all the logic back into the handlers, which is what the reducer was meant to fix.

Was this article helpful?

Your response is saved on this device.