Course contentsShow
← React
Lesson 1011 of 2,39626. Rules of Hooks Deep DiveFree lesson

Demonstrating Hook Misalignment

A concrete example showing how conditional hooks assign state to the wrong variables.

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: name state → "Alice"
  • Hook slot 1: theme state → "dark"
  • Hook slot 2: count state → 0

Second render (isGuest = true):

  • Hook slot 0 is skipped (condition is false)
  • Hook slot 0: theme tries to read slot 0 → gets "Alice" (!!)
  • Hook slot 1: count tries 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.