React ยท Chapter 20 of 42

Rules of Hooks

React hooks must follow two essential rules: only call hooks at the top level (never inside loops, conditions, or nested functions), and only call hooks from React function components or custom hooks.

These rules ensure React can correctly associate state between renders, since hooks rely on consistent call order.

Rule 1: Top level only

Never call hooks inside if statements, loops, or nested functions โ€” always call them at the top level of the component so their order stays consistent every render.

Rule 2: Only from React functions

Call hooks only from function components or other custom hooks, not from regular JavaScript functions or class components.

Example 1 (jsx)
// โŒ Wrong: conditional hook call
function Bad({ show }) {
  if (show) {
    const [x, setX] = useState(0); // breaks call order
  }
  return null;
}

// โœ… Correct
function Good({ show }) {
  const [x, setX] = useState(0);
  if (!show) return null;
  return <p>{x}</p>;
}
Output
(Good renders correctly, Bad violates hook rules)

Hooks must always run in the same order on every render.

Key points

  • Only call hooks at the top level, never in conditions or loops.
  • Only call hooks from function components or custom hooks.
  • React relies on consistent call order to track state per hook.
  • The eslint-plugin-react-hooks plugin catches most violations automatically.
๐Ÿ’ก Note: Install eslint-plugin-react-hooks to get automatic warnings for rule violations.

๐Ÿ“ Quick Quiz

1. Where should hooks be called?

2. Why does call order matter for hooks?

3. Which tool helps catch hook rule violations?