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

Why Conditional Hooks Break Everything

How a hook that sometimes doesn't run causes index misalignment and state corruption.

Why Conditional Hooks Break Everything

You'll learn: How running a hook conditionally destroys React's index-based system and corrupts your component's state.

The Fatal Mismatch

Remember that React stores hooks in an internal array, using the call order as the index. On the first render, React builds this array. On every re-render, React expects hooks to be called in exactly the same order so it can match each hook call to the correct stored value.

When you conditionally skip a hook, you create a devastating index mismatch.

The Corruption Scenario

function Profile({ isLoggedIn }) {
  const [name, setName] = useState('Alice'); // Hook index 0
  
  if (isLoggedIn) {
    const [email, setEmail] = useState(''); // Hook index 1 (sometimes)
  }
  
  const [theme, setTheme] = useState('dark'); // Hook index 1 or 2?
}

First render (logged in):

  • Index 0: name state
  • Index 1: email state
  • Index 2: theme state

Second render (logged out):

  • Index 0: name state
  • Index 1: theme state ← Receives email's stored value!
  • Index 2: (missing) ← React panics

Your theme state now contains email data. React's entire hook system is now corrupted for this component.

Why It's Catastrophic

This isn't just a bug—it's data corruption. State values get assigned to the wrong variables. Effects run with wrong dependencies. The component becomes unpredictable. React detects this and throws an error, but only because the hook count changed. The damage would be silent if the count stayed the same but the types shifted.

Key Takeaway: Conditional hooks break the index-to-hook mapping that React relies on, causing state corruption and system failure. Always call hooks in the same order, every render.