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

The Two Cardinal Rules of Hooks

Only call hooks at the top level and only call hooks from React functions—the foundational constraints.

The Two Cardinal Rules of Hooks

You'll learn the two fundamental rules that govern where and how you can call hooks in React—violate these, and your app will break.

Why Hooks Have Rules

React hooks aren't magic—they rely on a precise calling order to maintain state consistently across renders. React tracks which state belongs to which hook by their position in the call stack, not by name. This means the order and conditions under which you call hooks must be predictable.

Rule #1: Only Call Hooks at the Top Level

Never call hooks inside loops, conditions, or nested functions. They must run in the same order every single render.

// ❌ WRONG
function MyComponent({ isLoggedIn }) {
  if (isLoggedIn) {
    const [user, setUser] = useState(null); // Conditional hook!
  }
}

// ✅ CORRECT
function MyComponent({ isLoggedIn }) {
  const [user, setUser] = useState(null); // Always called
  if (isLoggedIn) {
    // Use the state conditionally instead
  }
}

Analogy: Think of hooks as numbered lockers. React assigns your data to locker #1, #2, #3 based on call order. If you skip locker #2 on Tuesday, everything gets stored in the wrong locker from then on.

Rule #2: Only Call Hooks from React Functions

Hooks must be called from either:

  • React function components
  • Custom hooks (which are themselves called from React functions)
// ❌ WRONG
function regularJavaScriptFunction() {
  const [count, setCount] = useState(0); // Not in React context!
}

// ✅ CORRECT
function useCounter() { // Custom hook
  const [count, setCount] = useState(0);
  return count;
}

Key Takeaway: Hooks must always be called in the same order (top level only) and only from React functions or custom hooks—these rules ensure React can reliably track your component's state across renders.