React · Lesson 58 of 120
Rules of Hooks
Top level only.
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.
| key | value |
|---|---|
| Top level | not in if or loops |
| Only from | components and hooks |
| Why | call order |
| Linter | eslint-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