EasyHooks📖 Theory Question

What are the Rules of Hooks and why do they exist?

💡

Hint

Only call at top level, only in React functions — React relies on call order to track state

Full Answer

Two rules enforced by the eslint-plugin-react-hooks linter:

  1. Only call hooks at the top level — never inside loops, conditions, or nested functions
  2. Only call hooks in React function components or custom hooks — not in regular JS functions

Why? React tracks hook state by call order. It uses an internal linked list — hook #1, hook #2, etc. If you call hooks conditionally, the order changes between renders and React's state gets mismatched:

// ❌ WRONG — conditional hook breaks the call order
function Profile({ userId }) {
  if (!userId) return null; // return before hook!
  const [user, setUser] = useState(null); // hook #1 sometimes skipped
}

// ✅ CORRECT — always call hooks, handle condition inside
function Profile({ userId }) {
  const [user, setUser] = useState(null); // hook #1 always
  if (!userId) return null;               // condition after hooks
}
💡 If you find yourself wanting a conditional hook, extract the conditional logic into a custom hook where you can return early after the hooks are already called.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint