liveBook · Manning

Rules of hooks

As explained in React Quickly, Second Edition

The Rules of Hooks are React usage constraints requiring hooks to be called unconditionally, in the same order, directly from a component or custom hook body.

The Rules of Hooks keep React hook calls predictable: call each hook every render, in the same order, directly inside a functional component or custom hook. section 5.2.1 section 7.8

Apply the rules with these checks:

  • Call hooks at the top level of a component; do not place them inside conditions, loops, or after an optional return. section 5.2.1 section 7.8
  • Call hooks only inside functional components or custom hooks, not ordinary helper functions or class-based components. section 7.7 section 7.8
  • Name custom hooks with the use prefix, such as useCounter. section 5.2.1

Move the early return below the hook

This breaks the rules because useState runs only when isVisible is true:\n\nfunction Counter({ isVisible }) {\n if (!isVisible) return null;\n const [counter, setCounter] = useState(0);\n}\n\nInitialize the hook on every render instead:\n\nfunction Counter({ isVisible }) {\n const [counter, setCounter] = useState(0);\n if (!isVisible) return null;\n return /* counter UI */;\n} section 5.2.1

How React Quickly, Second Edition covers it

How deep it goes
Explains top-level placement, render-to-render ordering, early returns, and component boundaries through a broken and corrected example.
Examples
Uses a Counter component whose isVisible prop creates an illegal conditional useState call and a corrected early-return version.
What it assumes
Assumes functional components and hook usage, while explaining conditional calls and custom-hook boundaries directly.
What you can do after
Apply the rules by moving hooks above conditions and returns, and by keeping hook calls inside components or custom hooks.
How it connects
Connects hooks with functional components, custom hooks, conditional rendering, early returns, and stateful hooks such as useState.

Also explained in

Compare how 2 books explain rules of hooks →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.