← Lessons

quiz vs the machine

Gold1350

Frontend

The Rules of Hooks

Why hooks must run in the same order on every render.

4 min read · core · beat Gold to climb

Hooks are positional

React does not pass hook names around. It tracks each hook by the order it is called within a component render. The first useState maps to slot one, the second to slot two, and so on.

The two rules

  • Only call hooks at the top level, never inside conditionals, loops, or nested functions.
  • Only call hooks from React function components or custom hooks.

If a hook runs conditionally, the call order shifts between renders and React reads the wrong slot. State and effects then get crossed.

Custom hooks

A custom hook is just a function that starts with use and calls other hooks. It follows the same ordering rules, which is why the naming convention matters for the linter.

Key idea

React matches hooks to state by call order, so keep every hook at the top level to keep that order stable.

Check yourself

Answer to earn rating on the learn ladder.

1. How does React associate a hook with its state?

2. Which is a violation of the rules of hooks?