Understanding Hook Rules
React stores hook state by call index during render. If order changes, state/effect associations can drift and behavior becomes undefined or broken.
Quick Navigation: Mechanics Behind the Rules • What Breaks and Why • Trade-offs, Edge Cases, Interview Takeaway
Quick Decision Guide
Rules of Hooks protect deterministic state slot mapping.
- Keep hook call order stable across renders - Keep render pure; move synchronization into effects - Use custom hooks to compose behavior without violating order
Interview signal: Explain why rules exist (state slot mapping), not just what rules say.
Mechanics Behind the Rules
🔥 Insight
The underlying mechanic is: order gives identity.
🧠 Mental Model
render #1: useState, useEffect, useMemo
render #2: useState, useEffect, useMemo // must match exactlyReact does not match hooks by variable name. It matches by position in the call sequence.
What Breaks and Why
Behavior Risks
// ❌ Wrong
if (isOpen) {
const [count] = useState(0)
}
// ✅ Correct
const [count] = useState(0)
if (!isOpen) return nullRules of Hooks (and why)
These rules follow from React's render model:
Trade-offs, Edge Cases, Interview Takeaway
Trade-offs
Edge Cases
🎯 Interview Takeaway
Say: Hooks depend on stable call order because React maps state/effects by render position.