The Anti-Pattern of Conditional Hooks
What you'll learn: Why wrapping hooks in if statements or conditionals breaks React and how to refactor your logic correctly.
The Core Rule: Hooks Must Be Unconditional
React has a strict requirement: hooks must be called in the exact same order every time your component renders. When you put hooks inside if statements, loops, or after early returns, you break this rule.
Why This Breaks React
React tracks hooks by their call order, not by their names. Imagine hooks like numbered slots: "First hook = useState for name, Second hook = useEffect for logging." If you conditionally skip the first hook on some renders, React gets confused—it expects the name state but receives the logging effect instead.
// ❌ WRONG: Hook inside conditional
function Profile({ isLoggedIn }) {
if (isLoggedIn) {
const [name, setName] = useState(''); // Sometimes called, sometimes not!
}
return <div>Profile</div>;
}
React will throw an error: "Rendered fewer hooks than expected."
The Fix: Move Conditions Inside Hooks
Keep hooks at the top level, unconditionally. Put your conditional logic inside the hook or after calling it:
// ✅ CORRECT: Hook called unconditionally
function Profile({ isLoggedIn }) {
const [name, setName] = useState(''); // Always called
if (!isLoggedIn) {
return <div>Please log in</div>; // Early return AFTER hooks
}
return <div>Welcome, {name}</div>;
}
The Analogy
Think of hooks like attendance at a meeting. React takes roll call in the same order every time. If someone randomly skips without warning, the whole list gets misaligned.
Key Takeaway: Always call hooks at the top level of your component, unconditionally. Move your if statements inside the hook logic or after all hooks have been called.