Understanding Hook Rules

Medium

React stores hook state by call index during render. If order changes, state/effect associations can drift and behavior becomes undefined or broken.

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 exactly

React does not match hooks by variable name. It matches by position in the call sequence.

What Breaks and Why

Behavior Risks

Conditional hook calls shift later hook indices
Early returns before hooks change call graph
Calling hooks in callbacks bypasses render-time ordering
// ❌ Wrong
if (isOpen) {
  const [count] = useState(0)
}

// ✅ Correct
const [count] = useState(0)
if (!isOpen) return null

Rules of Hooks (and why)

Call hooks at the top level of React components or custom hooks.
Do not call hooks inside conditions, loops, or nested functions.
Only call hooks from React function components or other custom hooks.

These rules follow from React's render model:

React relies on consistent hook call order across renders.
Hook identity is tied to position in the render sequence.
Conditional or reordered hook calls can misassociate state/effects and produce incorrect behavior.

Trade-offs, Edge Cases, Interview Takeaway

Trade-offs

Strict rules improve predictability and tooling
But they force structural discipline in component design

Edge Cases

Custom hooks can call hooks safely because they execute during render
Dynamic hook lists are invalid even if they "seem to work" locally

🎯 Interview Takeaway

Say: Hooks depend on stable call order because React maps state/effects by render position.

Key Takeaways

1Hook rules encode runtime invariants, not style preferences.
2Hook identity is call order, not variable naming.
3Custom hooks are safe because they run in render call graph.
4Interviewers look for mechanism-first explanations.