178
Top Answer
The Two Rules of Hooks
1. Only call hooks at the top level
Don't call hooks inside loops, conditions, or nested functions.
// ❌ BAD
if (condition) {
const [state, setState] = useState(0);
}
// ✅ GOOD
const [state, setState] = useState(0);
if (condition) {
// use state here
}
2. Only call hooks from React functions
Only call hooks from React function components or custom hooks.
Why These Rules Exist
React relies on the order hooks are called to match state with the correct hook. If hooks are called conditionally, the order can change between renders:
// First render: useState(0), useState('')
// Second render: useState('') ← Wrong state!
React stores hook state in a linked list. Each hook "claims" the next slot. If order changes, hooks get wrong values.
ESLint Plugin
Use eslint-plugin-react-hooks to catch violations automatically.
HooksExpert