The Rules of Hooks

Two rules, one reason. Call hooks at the top level of a component or another hook, and call them in the same order every render.

The reason is that React matches state to hooks by the order they are called. There are no names involved. A hook that sometimes does not run shifts everything after it onto the wrong state.

Conditional hooks

Broken

// wrong: sometimes skipped
if (signedIn) {
  const [n, setN] = useState('');
}

Fixed

// right: always called
const [n, setN] = useState('');

if (signedIn) {
  // use n here
}
Compare → Move the condition inside, not around the hook. The same applies to loops, early returns placed above a hook, and nested functions.

Where hooks may be called. In components, and in other hooks. Not in plain helper functions, not in event handlers, not in effects.

The eslint plugin catches every violation of both rules. Install it and believe it: this is not a case where you know better than the linter.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back