Calling Hooks Inside Conditionals
You'll learn why wrapping useState or useEffect in an if statement causes React's hook tracking system to break catastrophically.
The Core Problem
React tracks your hooks by position and call order, not by name or any other identifier. When you call hooks conditionally, their order changes between renders — and React has no way to match up which hook state belongs to which hook call anymore.
Remember React's index-based hook registry from earlier lessons? On first render, React records hooks in order: slot 0, slot 1, slot 2. On re-render, React expects the exact same sequence. An if statement that sometimes skips a hook creates misalignment:
// ❌ BROKEN: Conditional hook call
function BrokenComponent({ isLoggedIn }) {
if (isLoggedIn) {
const [user, setUser] = useState(null); // Sometimes slot 0, sometimes skipped
}
const [count, setCount] = useState(0); // Sometimes slot 0, sometimes slot 1
// React is now confused about which state belongs where
}
Why This Fails
On first render when isLoggedIn is true, React stores two pieces of state in slots 0 and 1. If isLoggedIn becomes false on re-render, React skips the first hook — but still expects slot 0 to be the user state. Instead, it finds the count hook trying to read from slot 0. Type mismatch. Data corruption. Complete chaos.
The solution? Always call hooks at the top level. Put conditional logic around the result, not the call:
// ✅ CORRECT: Hook called unconditionally
function CorrectComponent({ isLoggedIn }) {
const [user, setUser] = useState(null);
const [count, setCount] = useState(0);
// Conditional logic uses the hook result
if (isLoggedIn && user) {
// ...
}
}
Key Takeaway: Conditional hook calls break React's position-based tracking system because they change the hook call order between renders, causing state and effects to become misaligned with unpredictable results.