How Does useState Work Under the Hood?
viaLeetCode
Prompt How does useState work under the hood — where does the state live, and why must hooks be called in the same order every render?
Be ready to discuss
- Storage: state lives on the component's Fiber node as a linked list of hook records; each useState call during render consumes the NEXT record in that list — the association is purely positional, there are no names/ids.
- Why order matters: a conditional hook shifts every subsequent call by one slot, so calls read the wrong record — that's the entire Rules-of-Hooks rationale; the mental model of "an array of hook cells with a cursor" is what interviewers want stated.
- Updates: setState enqueues an update on that hook's queue and schedules a re-render; on the next render useState returns the reduced (final) queued value. Updates are batched (React 18: batched everywhere, including timeouts/promises).
- Functional updates: setCount(c => c+1) reads the queued latest value; setCount(count+1) closes over a stale snapshot — demonstrate the double-increment-in-one-click bug and fix.
- Mount vs update paths: first render creates the hook record with the initial value (lazy initializer runs once); subsequent renders ignore the initial argument.
- Adjacent probes: why setState with the same value can still render once more, Object.is bailout, and how useReducer is the same mechanism with an explicit reducer.
asked …