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

Why Hooks Must Be Called in Order

React tracks hook state by call order, not name—understand the internal mechanism that necessitates the rules.

Why Hooks Must Be Called in Order

What you'll learn: How React internally tracks hook state by call order, making the "always call hooks in the same order" rule absolutely critical.

React's Internal Hook List

When your component renders, React doesn't track hooks by their variable names. Instead, it maintains an internal linked list of hook calls in the exact order they occur.

function MyComponent() {
  const [name, setName] = useState('');     // Hook #1
  const [age, setAge] = useState(0);        // Hook #2
  useEffect(() => { /* ... */ }, []);       // Hook #3
  const toggle = useToggle(false);          // Hook #4
}

React creates a mental map: "First useState is for 'name', second is for 'age', third is the effect, fourth is the custom hook." On re-renders, React walks through this list again—it assumes the same hooks are called in the same order.

What Happens If Order Changes

If you conditionally call a hook:

function BrokenComponent({ show }) {
  const [name, setName] = useState('');
  
  if (show) {
    const [age, setAge] = useState(0);  // ❌ Position changes!
  }
  
  useEffect(() => { /* ... */ }, []);
}

When show toggles, the age hook disappears or reappears. React's internal counter gets misaligned—it might assign age's state to the effect on next render, causing catastrophic state corruption.

The Analogy: A Numbered Locker System

Imagine React uses numbered lockers (1, 2, 3...) to store hook data. Your code must always claim the same locker numbers in the same order. If you skip locker #2 one day, you'll retrieve the wrong contents from locker #3.

Key Takeaway: React identifies hooks by their call position, not variable name—consistent order is how React matches state to hooks across renders.