← Back to React, page 7

react-0128 · Hard senior

How do hooks work under the hood, and why do the rules of hooks require the same call order on every render?

React stores a component's hook state in an ordered list attached to its fiber. Each call to useState or useEffect reads the next slot in that list, because hooks have no names or keys, only their position. If the order or the number of calls changes between renders, a call reads the wrong slot, so React throws or returns another hook's state. That is why hooks must not be called in conditions, loops or after early returns.

Full answer

A hook such as useState(0) does not know which component called it. React tells it: during rendering, React sets a "current component" and a dispatcher. Inside it, each hook call looks at the component's list of hook records, one per call, and uses the next one.

In React's implementation, the fiber for a component has a memoizedState field that points to the first hook object. Each hook object holds its state (for useState, the value and an update queue) and a next pointer to the following hook, forming a linked list. On the first render (mount), each call creates a new node and appends it. On later renders (update), the calls walk the list from the start, one node per call, and reuse the stored state. The "cursor" is just position in the call order.

Consequences:

  • Calling hooks in the same order on every render keeps each call attached to the same node. That is the rule of hooks, and the lint rule enforces it.
  • A conditional hook shifts every following call by one. A later useState('b') then receives the node that belonged to another call, and React reports "Rendered fewer hooks than expected" or "Rendered more hooks than during the previous render".
  • Hooks cannot be called outside a render because there is no current fiber and dispatcher. That explains the invalid hook call error, which also happens with two copies of React (the hook uses the other copy's dispatcher).
  • State belongs to the component instance at a position in the tree, not to the hook name. Renaming variables does not matter, reordering calls does.
  • Effects have nodes too (with dependency arrays), and React compares dependencies per node.

Design benefits: composition. Custom hooks are only functions that call other hooks, so their state is simply appended to the same list. Two uses of one custom hook in a component create independent slots.

The example builds a tiny version with an array and a cursor, shows the shift caused by a conditional hook, then confirms with real React.

jsx
import { useState } from 'react';
import { createRoot } from 'react-dom/client';

// Part 1: a miniature model of hooks. State lives in a list, and a cursor follows the call order.
let slots = [];
let cursor = 0;

function useMiniState(initial) {
  const index = cursor++;
  if (!(index in slots)) slots[index] = initial;
  return [slots[index], (value) => (slots[index] = value)];
}

function render(component) {
  cursor = 0;
  return component();
}

let showExtra = true;
function MiniComponent() {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  if (showExtra) useMiniState('extra hook');
  const [name] = useMiniState('Asha');
  return name;
}

console.log('mini render 1 (extra hook called): ' + render(MiniComponent));
showExtra = false;
console.log('mini render 2 (extra hook skipped): ' + render(MiniComponent));

// Part 2: the same mistake in real React.
let callExtra = true;
function RealComponent() {
  if (callExtra) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useState('extra');
  }
  const [name] = useState('Asha');
  return <p>{name}</p>;
}

const root = createRoot(document.getElementById('root'), {
  onUncaughtError: (error) => console.log('real React: ' + error.message.split('\n')[0]),
});
root.render(<RealComponent />);
await new Promise((resolve) => setTimeout(resolve, 30));
callExtra = false;
root.render(<RealComponent />);
await new Promise((resolve) => setTimeout(resolve, 30));

Part 1 uses an array with a cursor instead of React's linked list, to show the principle. In part 2 the real React in development reports the changed hook count. The lint rule is disabled on purpose in this file to show the mistake. Output of the run: mini render 1 (extra hook called): Asha mini render 2 (extra hook skipped): extra hook real React: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

Key points

  • Hook state is an ordered list on the component's fiber. The call order is the only identifier.
  • Mount creates nodes in order. Updates walk the same list from the start.
  • A conditional hook shifts later calls onto the wrong nodes, which is why call order must be stable.
  • Hooks need a current render and a single copy of React, or they throw an invalid hook call error.
  • Custom hooks work because they just append more nodes to the same list.

Common mistakes

  • Calling hooks inside conditions, loops or after an early return.
  • Reordering hook calls during a refactor without noticing.
  • Loading two copies of React and getting an invalid hook call error.
  • Calling hooks from regular functions or event handlers.
  • Assuming state is attached to the variable name.

Follow-ups

  • Why do custom hooks not need a special mechanism?
  • How does React know which dependencies array belongs to which effect?
  • What would a hooks system with named keys look like, and what would it cost?

Tips

  • Say "an ordered list per component" and "position is the identity".
  • Explain the conditional hook failure with the shifted slot.
  • Mention duplicate React copies as another cause of invalid hook calls.