Question presented to candidate:
"You have a component whose state is getting messy — half a dozen useState calls that keep having to change together. When would you reach for useReducer instead, and what does that actually buy you?"
What a strong answer should cover:
- Both add local state to a function component; they are equivalent in power.
useStatefits simple, independent values updated directly.useReducercentralises transitions in a pure reducer(state, action) => newState; componentsdispatchintent rather than computing the next state.- The real payoff: the reducer is a pure function testable with no React at all, and branchy transitions live in one place.
dispatchhas a stable identity across renders, so it can be passed down without breakingReact.memo— the same is true of theuseStatesetter.- Multiple dispatches in one handler are batched into a single re-render.
- Signal of depth:
useStateis implemented on the same underlying machinery asuseReducer.
Clarifying questions expected:
- "Do these state fields have to change together, or are they genuinely independent?"
- "Is this state local, or does it need to be shared — in which case is a reducer plus context the right shape?"
Code / implementation expected: Yes — a small reducer with two or three action types, and the dispatch call site.