The rules of hooks

Why call order matters, and how React's real useState maps to the toy.

Builds on Hooks from scratch.

Hooks from scratch put useState on the toy. State sits in slots on the component's fiber, each call finds its slot by call order, and the setter queues an update and schedules a render. That design works, and it has a price. React states the price as two rules that most developers have memorized without ever seeing the reason.

This chapter derives both rules from the toy, breaks one on purpose to watch what goes wrong, then maps the toy's useState onto React's real implementation: a linked list of hooks, a dispatcher that swaps between mount and update code, lanes on the update queue, and a bailout with two layers. The next chapter adds useEffect to the same slots.

Why the rules of hooks exist#

React's two rules of hooks are usually taught as rules. With the toy in front of you, they're consequences:

  1. Only call hooks at the top level, not inside conditions, loops, nested functions, try/catch blocks, or after an early return. The slot is chosen by call order. If a hook call is skipped on one render, every hook after it reads its neighbor's slot (step through the diagram below).
  2. Only call hooks from components or custom hooks. A hook finds its component through wipFiber, which is only set while the renderer is calling a component. Called from an event handler, a timer or any other code that runs outside a render, there's no fiber to attach to. Naming custom hooks useSomething is what lets you, and the linter, tell which functions call hooks and therefore have to follow rule 1 too.
Hook slots across renders
Render 1 · showNickname = truefiber.hooksuseState("Ada")useState("The Countess")useState(36)0"Ada"1"The Countess"236createcreatecreatehookIndex: 0, 1, 2
Step 1 of 4

First render. Each useState call creates the next slot in fiber.hooks while hookIndex counts 0, 1, 2. Nothing records which line of code made which slot. The only link is the order of the calls.

Here's rule 1 broken on the toy. Toggle the nickname.

A conditional hook, on the toy
import { createElement, render, useState } from "./toy.js";

function Profile({ showNickname }) {
  const [name] = useState("Ada");
  if (showNickname) {
    const [nickname] = useState("The Countess"); // conditional: breaks the rule
  }
  const [age] = useState(36);
  return <p>{name}, age {age}</p>;
}

let showNickname = true;
const root = document.getElementById("root");
function draw() {
  render(
    <div>
      <button onClick={() => { showNickname = !showNickname; draw(); }}>
        Toggle nickname (now {showNickname ? "on" : "off"})
      </button>
      <Profile showNickname={showNickname} />
    </div>,
    root,
  );
}
draw();

The toy happily renders "Ada, age The Countess". React would refuse. When a component renders fewer hooks than last time, React throws "Rendered fewer hooks than expected", and more hooks throws "Rendered more hooks than during the previous render". In development it also records the sequence of hook types and warns when they change order. The ESLint plugin eslint-plugin-react-hooks catches most violations before you run anything.

Conditional logic is fine; it just goes inside or after the hooks, never around them: call useState unconditionally and decide what to do with the value.

Fix itSigning out crashes the profile

This is real React now. Press Sign out and the whole app disappears; the console shows the error React throws. Fix Profile so signing out shows "Signed out." and signing back in works, without changing what the profile does. Press Check when you think it works.

import { useState } from "react";

const ada = { name: "Ada Lovelace", bio: "Wrote the first published program." };

function Profile({ user }) {
  const [showBio, setShowBio] = useState(false);
  if (!user) return <p>Signed out.</p>;

  const [likes, setLikes] = useState(0);
  return (
    <section>
      <h2>{user.name}</h2>
      <button onClick={() => setLikes(likes + 1)}>Like ({likes})</button>
      <button onClick={() => setShowBio(!showBio)}>{showBio ? "Hide bio" : "Show bio"}</button>
      {showBio && <p>{user.bio}</p>}
    </section>
  );
}

export default function App() {
  const [user, setUser] = useState(ada);
  return (
    <div>
      <button onClick={() => setUser(user ? null : ada)}>{user ? "Sign out" : "Sign in"}</button>
      <Profile user={user} />
    </div>
  );
}

The real thing: useState in React#

React's implementation is the toy's with more care for priorities and correctness. Mapped piece by piece:

  • The slots are a linked list, not an array. A function component fiber's memoizedState points to its first hook, and each hook object ({ memoizedState, baseState, baseQueue, queue, next }) points to the next. The toy's hookIndex corresponds to React walking two pointers at once: currentHook along the current fiber's list and workInProgressHook along the new one.
  • wipFiber is currentlyRenderingFiber, set by renderWithHooks before your component is called.
  • Hooks go through a dispatcher. useState imported from react doesn't contain the logic. It calls ReactSharedInternals.H.useState, and React points H at a mount implementation on a component's first render (HooksDispatcherOnMount) and an update implementation afterwards (HooksDispatcherOnUpdate). Outside of rendering there's no dispatcher at all, so React logs "Invalid hook call. Hooks can only be called inside of the body of a function component." in development and the call then fails. While React renders something that isn't a function component, such as a class component, it installs a dispatcher whose hooks throw that same error.
  • The queue is a circular linked list of updates, each tagged with a lane (its priority). During a render React applies only the updates whose lanes are included in that render and keeps the rest (baseQueue, baseState) for later. That's how a transition can be rendered later than an urgent update to the same state without losing either.
  • setState is dispatchSetState bound to the fiber and queue, created once on mount and returned on every render. Same identity forever, as in the toy.
  • The Object.is bailout has two layers. If the fiber has no pending work, React computes the new state eagerly when you call the setter and returns early if it's equal, exactly the toy's check. Otherwise it renders the component and, if the state turns out equal and nothing else changed, throws the result away without rendering its children. The docs warn that "React may still need to call your component before skipping the children"; that second layer is why.
  • Batching: since React 18, with createRoot, all updates are batched automatically, whether they come from React event handlers, timeouts, promises or native listeners. React waits until the handler finishes, then renders once. flushSync(() => setState(x)) forces an immediate render when you really need the DOM updated before the next line.

See batching and the bailout in real React. The console logs each render:

Batching and bailouts in React
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  console.log("render, count =", count);

  return (
    <div style={{ display: "grid", gap: 6, maxWidth: 280 }}>
      <p>count: {count}</p>
      <button
        onClick={() => {
          setCount(count + 1);
          setCount(count + 1);
          setCount(count + 1);
        }}
      >
        setCount(count + 1) three times
      </button>
      <button
        onClick={() => {
          setCount((c) => c + 1);
          setCount((c) => c + 1);
          setCount((c) => c + 1);
        }}
      >
        {"setCount(c => c + 1) three times"}
      </button>
      <button onClick={() => setTimeout(() => { setCount((c) => c + 1); setCount((c) => c + 1); }, 0)}>
        Two updates in a timeout
      </button>
      <button onClick={() => setCount(count)}>Set the same value</button>
    </div>
  );
}
Nothing logged yet.

Each button that changes the count logs exactly one render, even the timeout one (before React 18, updates outside React event handlers rendered once per setState). Set the same value usually logs nothing at all. The first time you press it right after a button that changed the count, though, you'll see one render log with no change on screen. The fiber's alternate still carries the lane from that earlier update, so the eager check is skipped; that's the second bailout layer, where React calls the component, sees the state is equal and discards the result. Press it again and nothing logs.

Pitfalls#

Check your understanding#

Quick checkWhy order matters

Why can't you call useState inside an if statement?

Explain it out loudWhy do the rules of hooks exist?

An interviewer asks: "Why can't you call a hook inside an if? What would break?"

Interview angle

Say it in 30 seconds

Hooks are matched to their state by call order: React keeps each component's hooks as a linked list on its fiber's memoizedState, and the Nth call during a render takes the Nth hook. That's the whole reason for the rules of hooks. Skip a call in a condition, loop or early return and every later hook reads its neighbor's state, so React throws when the count changes. Hooks also need a component in progress, found through a dispatcher React installs only while rendering. Underneath, updates carry lanes so urgent and transition updates can share state, and setting an equal value bails out in two layers.

Why do the rules of hooks exist?

basic

What happens when you call setState with the same value?

intermediate

What does the "Invalid hook call" error mean, and what causes it?

intermediate

An urgent update and a transition both change the same piece of state. How does React keep both?

senior

Recap#

  • Hooks are matched to their slots by call order, so they must run at the top level of a component or custom hook: no conditions, loops or early returns around them.
  • A hook finds its component through the fiber React is rendering. Outside a render there's no dispatcher, so React reports "Invalid hook call".
  • React stores hooks as a linked list on fiber.memoizedState and walks it with currentHook and workInProgressHook. It throws when the count changes.
  • Updates carry lanes. A render applies only the lanes it includes and keeps the rest in baseQueue, which is how an urgent update and a transition can share a piece of state.
  • The Object.is bailout has two layers: an eager check in the setter, and a render that's thrown away when the state turns out equal.
  • Since React 18, every update is batched, including ones from timeouts, promises and native listeners.

Sources#