Why must a reducer function be pure, and what breaks if it is not?
React may call a reducer more than once with the same inputs, for example in Strict Mode. A pure reducer returns a new state from state and action only. Mutating state or running side effects inside it gives wrong or duplicated results.
Explain it simply
A reducer is like a bank passbook entry: given the old balance and a transaction, the new balance is fixed. If the clerk also sent an SMS or edited an old line while calculating, repeating the calculation would repeat the SMS or corrupt the history.
React can replay reducer calls, for example twice in Strict Mode during development, and it compares old and new state by reference. If you mutate the old object and return it, React sees the same reference, decides nothing changed, and skips the update. The screen stays stale.
So the rule is simple: build a new object or array from the old one, do not touch the old one, and do nothing else. Network calls, logging to a server, timers and random numbers belong in the event handler or an effect, not inside the reducer.
Example
function bad(state, action) {
state.count++; // mutation
return state; // same reference: no re-render
}
function good(state, action) {
if (action.type === "inc") return { ...state, count: state.count + 1 };
return state;
}What to say in the interview
"The reducer must be a pure function: the same state and action give the same new state, with no mutation and no side effects. React can invoke it twice in Strict Mode and relies on reference comparison to detect change. I copy objects with spread and keep API calls in handlers or effects."
Common mistakes
- Pushing into the existing array inside the reducer.