AI Hints
Home›React Tutorial›Hooks Rules and TypeScript
React · Lesson 58 of 120

Rules of Hooks

Top level only.

⏱ 2 min read▶ Video at 47:46🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Hooks have two rules. Break them, and state ends up in the wrong place. React keeps track of hooks by the order they're called, so that order must never change.

  • Two rules
  • Order matters
  • Never change it

The two rules

Only call hooks at the top level of a component, never inside conditions, loops, or nested functions. And only call them from React components, or from custom hooks. A linter plugin checks both for you.

keyvalue
Top levelnot in if or loops
Only fromcomponents and hooks
Whycall order
Lintereslint-plugin-react-hooks

Conditions

Putting a hook inside an if means it's called on some renders, and not others. Instead, always call the hook, and put the condition inside it, or after it.

Wrong

  • if (open) { const [x] = useState(0)}

Right

  • const [x] = useState(0)if (open) { ... }Same order

Summary

Call hooks at the top level, and only from components or custom hooks. Next, the hooks quiz.

Key takeaways
  • Top level
  • Same order
  • Use the linter
Next up: Hooks Quiz — test yourself