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
- Condition inside the hook:
useEffect(() => { if (!isOpen) return; ... }, [isOpen]). - Always call, ignore the result when not needed.
- Conditional components:
{isAdmin && <AdminTools />};AdminToolshas its own hooks. - Pass a flag to custom hooks:
useQuery({ enabled: !!userId })(TanStack Query) or anullkey in SWR. use()(React 19) for reading promises or context can be called insideif, 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
1import { use, useEffect, useState } from "react";2import { ThemeContext } from "./theme";34export function Panel({ isOpen, userId }: { isOpen: boolean; userId?: string }) {5 // Wrong: conditional hook6 // if (isOpen) { useEffect(() => trapFocus(), []); }78 // Right: hook always called, condition inside9 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]);1516 const [notes, setNotes] = useState("");1718 if (!isOpen) return null;1920 // OK: `use` may be called after an early return or inside conditions (React 19)21 const theme = use(ThemeContext);2223 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.