Course contentsShow
← React
Lesson 979 of 2,39625. Custom HooksFree lesson

Dynamic Hook Counts Break Everything

The number of hooks must be stable across renders—adding or removing hooks conditionally causes corruption.

Dynamic Hook Counts Break Everything

What you'll learn: Why changing the number of hooks between renders causes React's internal tracking to fail catastrophically.

The Core Problem

React tracks hooks by call order, not by name or location. It maintains an internal list: "first hook is useState, second is useEffect, third is useCallback..." When you render again, React walks through this exact same list in the same order, matching each hook call to its stored state.

If you conditionally add or remove a hook, the count changes. Now React's list doesn't match reality. The third hook might be reading state that belonged to the fourth hook last time. Everything becomes corrupted.

What Breaking the Count Looks Like

function BrokenComponent({ isLoggedIn }) {
  const [name, setName] = useState('');
  
  // ❌ WRONG: Hook count changes based on condition
  if (isLoggedIn) {
    const [email, setEmail] = useState('');
  }
  
  const [age, setAge] = useState(0);
  // React is now confused about which state belongs where
}

When isLoggedIn is true, React sees 3 useState calls. When false, only 2. The age state shifts positions in React's internal list, and chaos ensues.

The Analogy

Imagine a coat check where you get numbered tickets. Coat #1, #2, #3. When you return, you hand over ticket #2 and expect your coat. But if someone skipped #2 today, you get handed the wrong coat. React's hook system works exactly this way—stable positions are everything.

The Fix

Always call the same hooks in the same order. Put conditional logic inside the hooks or around the values, never around the hook calls themselves.

Key Takeaway: The number of hooks must remain constant across all renders—React relies on stable call order to track state correctly.