React / 26
The rules of hooks
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
Only call hooks at the top level
Not insideif, loops, nested functions, event handlers ortry/catch, and not after an earlyreturn. Every render must call the same hooks in the same order.Only call hooks from React functions
That means function components and custom hooks (your own functions whose names start withuse). 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"
useState("Asha")
useEffect(save)
useState("dark")
Render 2
name is "" (effect skipped)
useState("Asha")
useState("dark")
React expected the effect here
(nothing)
React expected a 3rd hook
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.
