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 the old line, repeating the calculation would repeat the SMS or corrupt history.
React can replay reducer calls, and it compares old and new state by reference. If you mutate and return the same object, React sees no change and skips the update.
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;
}Fetch calls, logging to a server or random numbers belong in the event handler, not the reducer.
What to say in the interview
"The reducer must be a pure function: 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.