Demonstrating Hook Misalignment
You'll learn how conditional hooks cause React to assign state values to the wrong variables, breaking your component.
The Broken Code
Let's see what happens when we break the "hooks must be called in order" rule:
function UserProfile({ isGuest }) {
// Conditional hook - BAD!
if (!isGuest) {
const [name, setName] = useState('Alice');
}
const [theme, setTheme] = useState('dark');
const [count, setCount] = useState(0);
// ...
}
What Actually Happens
First render (isGuest = false):
- Hook slot 0:
namestate → "Alice" - Hook slot 1:
themestate → "dark" - Hook slot 2:
countstate → 0
Second render (isGuest = true):
- Hook slot 0 is skipped (condition is false)
- Hook slot 0:
themetries to read slot 0 → gets "Alice" (!!) - Hook slot 1:
counttries to read slot 1 → gets "dark" (!!) - Hook slot 2: doesn't exist yet
React's internal hook registry doesn't know you skipped a hook. It just reads the next value in its index-based array. Your theme variable now contains the name value, and count contains the theme value—complete chaos.
The Misalignment Cascade
Each hook after the conditional one reads the wrong slot. If you try to call setTheme('light'), you're actually updating the name state. The component breaks in unpredictable ways, and React usually throws an error about hook count mismatches.
Key Takeaway: Conditional hooks cause React's index-based hook storage to misalign, assigning state from one variable to another and breaking your component entirely. Always call hooks in the same order every render.