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
- 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. - Be pure. The same state and action always give the same result. No
Date.now(),Math.random(), network calls or logging in a reducer. - Handle every case, and throw on unknown actions. A misspelled action type should fail loudly, not silently do nothing.
- Name actions after what happened, in the past tense:
card_moved, notsetColumn. 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.
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:
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:
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
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.
Spot the rule
Which rule does each of these break?
case "card_added": return [...cards, { id: Date.now(), title: action.title }];case "card_moved": cards[0].column = "done"; return [...cards];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
- Purity.
Date.now()belongs in the handler, and the id goes in the action. - 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.
- Name what happened.
set_cardsmoves all the logic back into the handlers, which is what the reducer was meant to fix.
Completion is saved in this browser only. It does not measure mastery.