What are the Rules of Hooks and why do they matter?
· Category: React
Short answer
There are two rules: only call hooks at the top level of a function, and only call hooks from React functions or custom hooks.
How it works
React relies on the order of hook calls to correctly associate state with components. Calling hooks inside loops, conditions, or nested functions breaks this deterministic ordering.
Example
// ❌ Bad
if (condition) {
useEffect(() => { ... });
}
// ✅ Good
useEffect(() => {
if (condition) {
// logic here
}
}, [condition]);
Why it matters
Violating the rules leads to subtle, hard-to-debug errors where state gets associated with the wrong hook or component. The eslint-plugin-react-hooks package automatically flags these issues.
Tips
- Enable the ESLint rule in your project and treat its warnings as errors.
- If you need conditional logic, move the condition inside the hook or early-return the whole component before any hooks are called.