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

Top-Level Only: Function Scope Requirements

Why hooks must be called at the top level of the component function, not in callbacks or loops.

Top-Level Only: Function Scope Requirements

What you'll learn: Why hooks must be called at the top level of your component function, not inside callbacks, loops, or conditional blocks.

The Function Scope Rule

Hooks must be called at the top level of your component or custom hook function. This means they must execute during the function's main body, not nested inside:

  • Callbacks (event handlers, setTimeout, promises)
  • Loops (for, while, map, forEach)
  • Conditional blocks (if, else, ternary operators)
  • Helper functions defined inside your component

Why This Restriction Exists

Remember React's index-based hook registry? React relies on hooks being called in the exact same order on every render. When you put a hook inside a callback or loop, you create situations where:

  1. Callbacks execute after render completes — the hook isn't called when React expects it
  2. Loops can execute different numbers of times — changing the hook count between renders
  3. Conditionals might skip hooks — breaking the call order invariant

Think of React's hook tracking like taking attendance in a classroom where students must sit in assigned seats. If students (hooks) only show up sometimes, or show up after attendance is taken (in callbacks), or the number of students changes (loops), the seating chart (hook registry) becomes meaningless.

The Correct Pattern

function MyComponent() {
  const [count, setCount] = useState(0); // ✅ Top level
  
  const handleClick = () => {
    setCount(count + 1); // ✅ Using the result, not calling the hook
  };
  
  // ❌ WRONG - hook in callback
  // const handleClick = () => {
  //   const [value] = useState(0);
  // };
}

Call hooks at the top level, then use their results (state, setters, refs) anywhere you need them.

Key Takeaway: Hooks must be called at the top level of your function component or custom hook to maintain React's call order invariant — use hook results in callbacks, loops, and conditionals, never call hooks themselves there.