Skip to content

Hooks in Depth ​

Explain why the rules of hooks exist, write an effect that cleans up correctly, and spot the stale closure before it ships.

In this chapter: why call order is the rule · useState against useRef · effects as synchronisation · stale closures · custom hooks that are worth extracting

💡 The Core Idea ​

A hook attaches something to a component instance: a value, a subscription, a piece of work. The component function itself holds no state and runs from top to bottom every render. The state lives outside it, in a list that React holds. React matches your hook calls to that list by call order.

Everything unusual about hooks follows from that one implementation detail. There is no name and no key. There is only "the third hook this component called". Change the order between renders, and the third call gets the second call's state.

This is why the rules are not style advice. useState inside an if is not just ugly. It is a use-after-free bug waiting for a branch to flip.

How It Works ​

The rules, and the one exception ​

RuleWhat breaks without it
Call hooks at the top level, never in a branch, loop or early returnCall order shifts and state is read from the wrong slot
Call hooks only from components or other hooksReact has no instance to attach the state to
Name custom hooks useSomethingThe linter and the React Compiler both rely on it

React 19 adds one deliberate exception: use may be called conditionally. It reads a promise or a context. It can appear inside an if or a loop, because it does not own a state slot. Every other hook still follows the rules above.

useState against useRef ​

Both survive re-renders. Only one of them causes a render.

NeedUseWhy
A value the UI showsuseStateChanging it must repaint the screen
A DOM node to focus, measure or playuseRefNot render output, and mutating it must not render
A timer id, a previous value, a scroll offsetuseRefTransient bookkeeping the UI never reads directly
An expensive initial valueuseState(() => build())The lazy form runs the builder once, not every render

The lazy initialiser is easy to miss. useState(buildIndex(rows)) calls buildIndex on every render and throws the result away after the first. useState(() => buildIndex(rows)) calls it once.

A ref for a value that changes too often to render:

tsx
const lastScrollY = useRef<number>(0);

function handleScroll(event: UIEvent<HTMLDivElement>): void {
  // Sixty writes a second, zero re-renders.
  lastScrollY.current = event.currentTarget.scrollTop;
}

⚠️ Never read or write ref.current during render. React makes no promise about when render runs or whether the result is kept. Read it in an event handler or an effect.

Effects synchronise; they are not lifecycle hooks ​

The useful way to read useEffect is: keep this external thing in step with this state. Not "run on mount". The dependency array is not a list of triggers you tune until the warning goes away. It is the list of values the effect uses. React re-synchronises whenever any of them differs.

Every effect that starts something must be able to stop it. The cleanup runs before the next synchronisation and again on unmount.

Subscribe, and unsubscribe on the way out:

tsx
useEffect(() => {
  const socket: RoomSocket = connect(roomId);
  socket.on("message", onMessage);
  return () => socket.close(); // Runs before the next roomId, and on unmount
}, [roomId, onMessage]);

Fetching needs the same discipline, because responses arrive out of order. Without the guard, a slow request for user 1 can overwrite a fast request for user 2.

Ignore a response that is no longer wanted:

tsx
useEffect(() => {
  const controller = new AbortController();

  void (async () => {
    const res: Response = await fetch(`/api/users/${userId}`, { signal: controller.signal });
    setUser((await res.json()) as User);
  })();

  return () => controller.abort();
}, [userId]);

Stale closures ​

Every render creates new functions, and each one closes over the values from that render. Some functions outlive the render that made them, such as an interval, a subscription or an event listener. Those keep reading the old values forever.

❌ The counter that stops at one:

tsx
useEffect(() => {
  const id: number = window.setInterval(() => {
    setCount(count + 1); // `count` is frozen at 0 from the first render
  }, 1000);
  return () => window.clearInterval(id);
}, []); // The empty array is what freezes it

✅ Do not close over the value at all:

tsx
useEffect(() => {
  const id: number = window.setInterval(() => {
    setCount((c: number) => c + 1); // React supplies the current value
  }, 1000);
  return () => window.clearInterval(id);
}, []);

Two fixes, one principle. Either put the value in the dependency array, so the effect re-runs with a fresh closure. Or stop reading the value and describe the change instead. Deleting a dependency to silence the linter picks neither and hides the bug.

Custom hooks ​

A custom hook is a function that calls hooks. That is the whole mechanism. There is no registry and no sharing. Two components calling useOnlineStatus() get two independent pieces of state.

Extract one when the logic repeats, not when the code only looks similar. A good custom hook hides a subscription, a synchronisation or a sequence of related state changes. Its name says what it does.

tsx
function useOnlineStatus(): boolean {
  return useSyncExternalStore(
    (onChange: () => void) => {
      window.addEventListener("online", onChange);
      window.addEventListener("offline", onChange);
      return () => {
        window.removeEventListener("online", onChange);
        window.removeEventListener("offline", onChange);
      };
    },
    () => navigator.onLine, // Value on the client
    () => true,             // Value on the server, so SSR and hydration agree
  );
}

useSyncExternalStore is the right tool whenever the data lives outside React: a browser API, a third-party store, a media query. It reads the value during render, not after it. So there is no flash of the wrong state, and no tearing (two parts of the screen showing different values) when React renders concurrently.

When to Use It ​

You needReach forNot
Value that drives the UIuseStateuseRef — nothing will repaint
Value that must not drive the UIuseRefuseState — a render per change
Data from a browser API or external storeuseSyncExternalStoreuseEffect + useState
A constant that never depends on propsModule scopeAny hook at all
Related state that changes togetheruseReducerFive useState calls kept in step by hand

Common Mistakes ​

❌ Trimming the dependency array to stop the effect re-running:

tsx
useEffect(() => {
  subscribe(roomId, onMessage);
}, []); // roomId and onMessage are used but not declared

The effect now describes a synchronisation it does not perform. ✅ Declare every value the effect reads, then make the unstable ones stable. Move the function inside the effect, hoist it out of the component, or wrap it in useCallback.

❌ Two useState calls that must always agree. If setting one without the other is a bug, they are one piece of state. ✅ Use useReducer, or derive the second from the first during render.

❌ Subscribing with an effect and mirroring into state. Two renders, a visible flash of the stale value, and a resubscribe on every dependency change. ✅ useSyncExternalStore.

❌ A custom hook that only groups unrelated calls. usePageSetup() wrapping four unrelated hooks hides the dependencies without simplifying anything. Extract behaviour, not lines.

🔑 Key Takeaways ​

  • React matches hooks to their state by call order, which is why they cannot sit inside a branch — use is the one React 19 exception.
  • useRef holds a value across renders without causing one; useState exists to cause one.
  • The dependency array lists what the effect reads; every effect that starts something must return the cleanup that stops it.
  • A stale closure is a function outliving the render whose values it captured — fix it with a fresh dependency or an updater function.
  • Data that lives outside React belongs in useSyncExternalStore, not in an effect that copies it into state.

Interview Questions ​

Q: Why can't hooks be called conditionally?

React stores hook state in a list per component instance. A hook call has no name or key, so React matches calls to entries by order. A conditional call shifts every later hook by one slot, so a useState would read another hook's value. React 19's use is exempt because it owns no slot. It reads a promise or context and stores nothing.

Q: This setInterval increments the counter to 1 and then stops. What is wrong?

The callback closes over count from the render in which the effect ran. The empty dependency array means the effect never re-runs. So that closure lives forever, with count frozen at its first value. The fix is to pass an updater function to setCount. It removes the dependency on the captured value, and it keeps the interval from being torn down and recreated every second.

Q: When would you choose useRef over useState for a value that changes?

When the UI does not read it during render. Examples are a drag offset updated on every pointer move, a timer id, or the previous value of a prop. These are all short-lived bookkeeping. Putting them in state means a render per change, for output nobody sees. The test is simple: if removing the value from the JSX changes nothing on screen, it does not belong in state.

Q: When is extracting a custom hook the wrong call?

When it only moves lines. A hook that wraps four unrelated calls hides which props and state the component depends on. It makes the effects harder to reason about, not easier. Extract when the logic is truly reused or self-contained, such as a subscription, a synchronisation or a state machine. Do not extract just because two components happen to call the same three hooks.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.