Skip to the page

State: snapshots, updates and where state lives · mid

How hooks store state: call order and the rules of hooks

React stores each component's hooks as an ordered list on its fiber and matches them by call index, so hooks must be called in the same order on every render: top level only, never inside conditions, loops or after an early return.

The notes

What you must know

  • Each hook call takes the next slot in a list. The slot holds the current value (memoizedState) and an update queue. React finds your state by position, not by variable name.
  • If a hook is skipped on one render (inside an if, or after an early return), every later hook reads the wrong slot. React throws a "rendered more/fewer hooks" error or shows wrong data.
  • Rules: call hooks only at the top level of function components and custom hooks. eslint-plugin-react-hooks checks this.
  • The setter from useState has a stable identity across renders; that is why it can be left out of effect deps.
  • useState is basically useReducer with a built-in reducer (state, action) => typeof action === "function" ? action(state) : action.
  • Lazy initial state useState(() => expensive()) runs the function only on the first render. useState(expensive()) runs it every render and ignores the result.
  • use() is the exception: it can be called inside conditions and loops, because it is not stored as an ordered state slot.

The red pen

Common traps: mistake → fix

  • Mistake: "Hooks use their variable name as the key"

    Fix: they use call order.

  • Mistake: "An early return before a hook is fine if it is rare"

    Fix: the render where it happens breaks the order.

  • Mistake: "A global variable is a fine useState implementation"

    Fix: state must be stored per component instance (per fiber).

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the rules of hooks?
  2. Which version throws a hook-order error: a conditional early return before useState, or after it?
  3. How does React store hook state between renders?
  4. Sketch a minimal useState implementation. Why is the setter stable? Why does state look stale in closures?
  5. Why can use() be called conditionally when useContext cannot?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview