So far the toy's components are pure functions of props, and every bit of changing data has lived outside them, in a state variable next to a render call. Real components need their own memory: whether this dropdown is open, what's typed in this field, which tab this panel shows. And each instance needs its own, so two counters don't share a count.
A function can't remember anything between calls by itself; its locals are gone when it returns. So the memory has to live somewhere that outlives a render and belongs to exactly one component instance. Chapter 7 built exactly that thing: the fiber. This chapter puts useState on it, and the famous rules of hooks fall out of the implementation.
The problem: components forget#
Here are the two obvious ways to give a component memory, on the stage 7 toy. Click each counter a few times.
import { createElement, render } from "./toy.js";
const root = document.getElementById("root");
const redraw = () => render(<App />, root);
// Attempt 1: a local variable.
function LocalCounter() {
let count = 0;
return <button onClick={() => { count++; redraw(); }}>Local: {count}</button>;
}
// Attempt 2: a module-level variable.
let shared = 0;
function SharedCounter() {
return <button onClick={() => { shared++; redraw(); }}>Shared: {shared}</button>;
}
function App() {
return (
<div>
<p><LocalCounter /> <LocalCounter /></p>
<p><SharedCounter /> <SharedCounter /></p>
</div>
);
}
redraw();The local counters never move: count is created fresh, as 0, every time the function runs. The module-level counters do count, but they count together, because there's one variable for every instance. What we need is a variable that persists across calls like the module-level one, but exists once per component instance like the local one.
Build it: useState on the fiber#
Where the state lives#
There's already one object per component instance that survives from render to render: its fiber. More precisely, its pair of fibers, current and work in progress, linked by alternate. So state goes on the fiber, in an array, one slot per useState call:
fiber.hooks = [hook0, hook1, ...]; // React keeps a linked list; same ideaWhen the component renders again, its work-in-progress fiber can read last render's slots through fiber.alternate.hooks.
Which slot is which#
A component might call useState three times. How does each call find its slot? The call doesn't pass a name or an id. It can't, without making every hook call verbose and every custom hook a naming hazard. So the toy, like React, uses the only thing left: call order. While a component renders, two variables track where we are:
let wipFiber = null; // the component being rendered right now
let hookIndex = 0; // how many hooks it has called so far
function updateFunctionComponent(fiber) {
wipFiber = fiber; // hooks called during this render belong to this fiber
hookIndex = 0;
fiber.hooks = [];
const children = toChildArray(fiber.type(fiber.props));
wipFiber = null;
reconcileChildren(fiber, children);
}The first useState call gets slot 0, the second slot 1, and so on. On the next render the same calls happen in the same order, so call N reads slot N. That's the whole mechanism. It's also why useState is just a function you import, not a method on the component: it finds the component through wipFiber, a variable the renderer sets before calling your function.
What's in a slot#
Each slot holds the current state and a queue of updates that haven't been applied yet:
export function useState(initialState) {
const oldHook = wipFiber.alternate?.hooks?.[hookIndex];
const hook = oldHook
? { state: oldHook.state, queue: oldHook.queue } // same queue every render
: {
state: typeof initialState === "function" ? initialState() : initialState,
queue: { pending: [], dispatch: null, lastRenderedState: undefined },
};
// Apply the updates queued since the last render, in order.
for (const action of hook.queue.pending) {
hook.state = typeof action === "function" ? action(hook.state) : action;
}
hook.queue.pending = [];
hook.queue.lastRenderedState = hook.state;
if (!hook.queue.dispatch) {
const queue = hook.queue;
const fiber = wipFiber;
queue.dispatch = (action) => {
// Bail out early: nothing queued, and the new state is the same value.
if (queue.pending.length === 0) {
const next = typeof action === "function" ? action(queue.lastRenderedState) : action;
if (Object.is(next, queue.lastRenderedState)) return;
}
queue.pending.push(action);
scheduleUpdate(fiber);
};
}
wipFiber.hooks.push(hook);
hookIndex++;
return [hook.state, hook.queue.dispatch];
}Walk through it once:
- First render (no old hook): create the state from
initialState. If it's a function, call it; that's lazy initialization,useState(() => expensiveDefault()), so the expensive work happens only once. - Later renders: start from the old state, then apply every queued action in order. An action is either a new value or an updater function that receives the previous state.
- The setter is created once and stored on the queue, which is shared by every render's hook object. So
setCountis the same function on every render, and calling a setter captured in an old closure still updates the right slot. React guarantees the same identity, which is why setters never need to be in dependency arrays. - Calling the setter doesn't render. It queues the action and calls
scheduleUpdate, which climbsreturnpointers to the root and queues a render of it. The new state is computed during that render. - The bailout. If nothing else is queued and the new value is the same as the current one by
Object.is, there's nothing to do, so the setter returns without scheduling anything.
scheduleUpdate reuses chapter 7's machinery:
function scheduleUpdate(fiber) {
let node = fiber;
while (node.return) node = node.return;
const container = node.dom;
if (!rootQueue.has(container)) rootQueue.set(container, null);
scheduleWork();
}(null means "re-render with the same root element as last time".) The toy re-renders the whole tree from the root. Real React starts from the root too, but skips quickly over every subtree with no pending updates; the toy doesn't have bailouts, so every component runs. That's a simplification, not a difference in what the user sees.
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 stage 8 running the counters from the start of the chapter, plus a small todo list that uses two pieces of state.
import { createElement, render, useState } from "./toy.js";
function Counter({ label }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount((c) => c + 1)}>
{label}: {count}
</button>
);
}
function Todos() {
const [todos, setTodos] = useState(["Buy milk"]);
const [text, setText] = useState("");
return (
<div>
<input value={text} placeholder="New todo" onInput={(e) => setText(e.target.value)} />
<button
onClick={() => {
if (!text) return;
setTodos([...todos, text]);
setText("");
}}
>
Add
</button>
<ul>
{todos.map((t) => (
<li key={t}>{t}</li>
))}
</ul>
</div>
);
}
function App() {
return (
<div>
<p>
<Counter label="A" /> <Counter label="B" />
</p>
<Todos />
</div>
);
}
render(<App />, document.getElementById("root"));Two counters, two fibers, two separate slots. The input keeps focus while you type, because the reconciler from chapters 5 to 7 keeps its DOM node, and its value comes from state.
Batching falls out for free#
Notice what happens when a click handler calls several setters. Each call pushes an action and calls scheduleUpdate, but scheduleWork only posts one message, and the render runs in a later task. By then all the actions are queued, so they're applied together in one render. That's batching: many state updates, one re-render.
It also explains the most common useState surprise. In the handler below, n is the value from the render that created the handler, a snapshot. Calling setN(n + 1) three times queues "set to 1" three times.
With the stage 8 toy, you click the button once. How many times does Counter render after the click, and what does the button show?
function Counter() {
const [n, setN] = useState(0);
console.log("render", n);
return (
<button
onClick={() => {
setN(n + 1);
setN(n + 1);
setN((x) => x + 1);
}}
>
{n}
</button>
);
}import { createElement, render, useState } from "./toy.js";
function Counter() {
const [n, setN] = useState(0);
console.log("render", n);
return (
<button
onClick={() => {
setN(n + 1);
setN(n + 1);
setN((x) => x + 1);
}}
>
{n}
</button>
);
}
render(<Counter />, document.getElementById("root"));Build useState yourself#
toy.js is stage 8 with useState taken out. Write it in useState.js, using the three pieces the renderer exports: currentlyRenderingFiber(), nextHookIndex() and scheduleUpdate(fiber). Your hook must keep separate state per component and per call, apply queued updates in order (including updater functions), return a setter that's the same function on every render, and skip the re-render when the new state is the same value. Press Check when you think it works.
import { currentlyRenderingFiber, nextHookIndex, scheduleUpdate } from "./toy.js";
export function useState(initialState) {
const fiber = currentlyRenderingFiber();
const index = nextHookIndex();
const oldHook = fiber.alternate?.hooks?.[index]; // this slot, last render
// TODO: build this render's hook from oldHook (or initialState),
// apply queued updates, store it in fiber.hooks[index],
// and return [state, setState].
return [typeof initialState === "function" ? initialState() : initialState, () => {}];
}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:
- Only call hooks at the top level, not inside conditions, loops, nested functions, 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 (the diagram above). - 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 a plain function or an event handler, there's no fiber to attach to.
Here's rule 1 broken on the toy. Toggle the nickname.
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.
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
memoizedStatepoints to its first hook, and each hook object ({ memoizedState, baseState, baseQueue, queue, next }) points to the next. The toy'shookIndexcorresponds to React walking two pointers at once:currentHookalong the current fiber's list andworkInProgressHookalong the new one. wipFiberiscurrentlyRenderingFiber, set byrenderWithHooksbefore your component is called.- Hooks go through a dispatcher.
useStateimported fromreactdoesn't contain the logic. It callsReactSharedInternals.H.useState, and React pointsHat 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. setStateisdispatchSetStatebound to the fiber and queue, created once on mount and returned on every render. Same identity forever, as in the toy.- The
Object.isbailout 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:
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>
);
}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#
Press Add. The list doesn't change. Fix it so each click adds an item. Press Check when you think it works.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([{ id: 1, text: "Buy milk" }]);
function add() {
const id = todos.length + 1;
todos.push({ id, text: `Todo ${id}` });
setTodos(todos);
}
return (
<div>
<button onClick={add}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>{t.text}</li>
))}
</ul>
</div>
);
}Check your understanding#
Why can't you call useState inside an if statement?
An interviewer asks: "A function component is just a function that runs on every render. How does useState remember its value between renders?"
Interview angle
A function component forgets everything between calls, so its state lives on its fiber, the object React keeps per mounted instance. Each hook call takes the next slot from a list on the fiber; in React it's a linked list on memoizedState. Slots are matched purely by call order, which is why hooks can't be conditional, in loops or after early returns. The setter is stable: it enqueues an update and schedules a render, so updates in one event are batched and only updater functions see earlier queued updates. If the new state is Object.is-equal to the old one, React bails out.
Where does useState store its state?
Why do the rules of hooks exist?
Is setState synchronous? Why does console.log after setState print the old value?
A component deep in the tree calls its state setter. How does that update reach the screen?
What happens when you call setState with the same value?
Why is the setter from useState stable across renders, and why does it matter?
Recap#
- Component state lives on the fiber, one slot per hook call. The work-in-progress fiber reads last render's slots through
alternate. - Slots are matched by call order (
hookIndexin the toy, a linked list onmemoizedStatein React). That's the reason hooks can't be conditional, in loops, or after an early return. - The setter enqueues an action and schedules a render; the render applies the queue in order. Updater functions see the latest queued state; plain values from the closure don't.
- Updates in the same event are batched into one render. Since React 18, that includes timeouts, promises and native listeners.
- If the new state is
Object.is-equal to the current one, React bails out. Mutating state and setting the same object therefore does nothing.
Sources#
- react.dev: useState, including the
Object.isbailout caveat - react.dev: State as a snapshot and Queueing a series of state updates
- react.dev: Rules of Hooks
- react.dev: React 18: automatic batching
- Rodrigo Pombo: Build your own React, step 8
- React source:
ReactFiberHooks.js - Facts checked November 24, 2026.