ReactEasy

Why hooks cannot be conditional?

Hooks cannot be called conditionally because React matches each hook call to its stored state purely by call order. If a condition skips a hook on some renders, the order shifts and later hooks receive the wrong state, producing bugs or errors such as "Rendered fewer hooks than expected".

Illustration

Render 1 calls useState(name), useState(email), useEffect. If on render 2 the name hook is skipped, React gives the email hook the stored name value and the effect the email slot. The data is silently mixed up.

Why React chose call order

  • No need to invent unique keys for every hook.
  • Custom hooks compose naturally: a hook can call other hooks and each gets its own slots.
  • It is fast and simple.

What to do instead

  1. Condition inside the hook: useEffect(() => { if (!isOpen) return; ... }, [isOpen]).
  2. Always call, ignore the result when not needed.
  3. Conditional components: {isAdmin && <AdminTools />}; AdminTools has its own hooks.
  4. Pass a flag to custom hooks: useQuery({ enabled: !!userId }) (TanStack Query) or a null key in SWR.
  5. use() (React 19) for reading promises or context can be called inside if, loops and after early returns.

Enforcement

The rules-of-hooks ESLint rule reports conditional hook calls at build time, and the React Compiler skips components that break the rules.

Code example

tsx
1import { use, useEffect, useState } from "react";
2import { ThemeContext } from "./theme";
3
4export function Panel({ isOpen, userId }: { isOpen: boolean; userId?: string }) {
5 // Wrong: conditional hook
6 // if (isOpen) { useEffect(() => trapFocus(), []); }
7
8 // Right: hook always called, condition inside
9 useEffect(() => {
10 if (!isOpen) return;
11 const onKey = (e: KeyboardEvent) => e.key === "Escape" && console.log("close");
12 window.addEventListener("keydown", onKey);
13 return () => window.removeEventListener("keydown", onKey);
14 }, [isOpen]);
15
16 const [notes, setNotes] = useState("");
17
18 if (!isOpen) return null;
19
20 // OK: `use` may be called after an early return or inside conditions (React 19)
21 const theme = use(ThemeContext);
22
23 return (
24 <div className={theme}>
25 {userId && <p>Editing as {userId}</p>}
26 <textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
27 </div>
28 );
29}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app