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

Top Level: No Conditionals, No Loops

Hooks cannot live inside if statements, loops, or nested functions—they must execute every render.

Top Level: No Conditionals, No Loops

You'll learn why React hooks must always execute in the same order, at the component's top level—never inside if statements, loops, or nested functions.

The Iron Law of Hooks Placement

Remember how hooks must be called in the same order every render? That requirement creates a strict placement rule: hooks must live at the top level of your component or custom hook function. They cannot be placed inside:

  • Conditional statements (if, else, ternary operators)
  • Loops (for, while, map callbacks)
  • Nested functions
  • Event handlers
  • Anything that might not execute every single render

Why This Matters

React tracks hooks by their call order, not by name or position in your source code. Think of it like taking attendance: React expects to see the same students (hooks) in the same order every day. If you put a hook inside an if statement, sometimes it shows up, sometimes it doesn't—React loses track of which hook is which.

// ❌ WRONG - hook inside conditional
function UserProfile({ userId }) {
  if (userId) {
    const [user, setUser] = useState(null); // Conditional hook!
  }
}

// ✅ CORRECT - hook at top level
function UserProfile({ userId }) {
  const [user, setUser] = useState(null); // Always called
  
  if (userId) {
    // Use the state here instead
  }
}

The logic that uses your hook's values can absolutely be conditional—just not the hook call itself.

Key Takeaway: Always call hooks at the top level of your function body, unconditionally. Use conditional logic after declaring hooks, not around them.