Skip to content
ClapelloNotes by Barath
ReactCh 05 · 5/6
Core3 min readUpdated

React / 26

The rules of hooks

TL;DR

Call hooks at the top level of a component or custom hook, never inside conditions, loops or nested functions, because React matches hooks by the order you call them.

The two rules

  1. Only call hooks at the top level

    Not inside if, loops, nested functions, event handlers or try/catch, and not after an early return. Every render must call the same hooks in the same order.
  2. Only call hooks from React functions

    That means function components and custom hooks (your own functions whose names start with use). Not plain helper functions, and not class components.

Why order matters

React keeps each component's hook data in a list, one slot per hook call. On every render it walks through your hook calls and hands out slots in order: first call, slot 1; second call, slot 2. There are no names involved: count and setCount are your names, and React never sees them.

const [name, setName] = useState("Asha");
if (name !== "") {
  useEffect(() => save(name)); // ❌
}
const [theme, setTheme] = useState("dark");

Render 1

name is "Asha"

#1

useState("Asha")

#2

useEffect(save)

#3

useState("dark")

Render 2

name is "" (effect skipped)

#1

useState("Asha")

#2

useState("dark")

React expected the effect here

#3

(nothing)

React expected a 3rd hook

React has no names for your hooks, only positions. Skip one call and every hook after it reads the wrong slot, so React throws an error.

On the second render the effect is skipped, so useState("dark") gets slot 2, which holds the effect's data. Here React notices the mismatch and throws an error. Worse cases exist: if two useState calls swap places, the types still line up, and your state is silently handed to the wrong variable.

Fixing the common mistakes

Don't

Hook after an early return

function Profile({ user }) {
  if (!user) return <p>Loading…</p>;
  const [tab, setTab] = useState("posts"); // skipped while loading
  return <Tabs value={tab} onChange={setTab} />;
}

Do

Hooks first, then return

function Profile({ user }) {
  const [tab, setTab] = useState("posts");
  if (!user) return <p>Loading…</p>;
  return <Tabs value={tab} onChange={setTab} />;
}

For a conditional effect (effects get their own chapter next), keep the hook unconditional and move the condition inside it:

useEffect(() => {
  if (name !== "") localStorage.setItem("name", name);
}, [name]);

Let the linter catch it

A linter flags hook rule breaks as you type. New Vite React projects use oxlint with react/rules-of-hooks switched on. ESLint projects (including Next.js) use eslint-plugin-react-hooks. If your editor underlines a hook in red, believe it.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.