Rules of Hooks
Last updated: 2026-11-02
Rules of Hooks Rules of Hooks
Hooks obey two iron rules: call them only at the top level of a function component or a custom Hook, never inside a loop, a condition or a nested function; and call them only from React functions, never from plain JavaScript functions. React matches each Hook to its state by call order, so once the order shifts the state gets crossed between slots and the UI updates the wrong value.
| Group | Routing & State Mgmt |
|---|---|
| Kind | Pattern |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
// ✅ Call unconditionally at the top level
function Counter() {
const [n, setN] = useState(0)
useEffect(() => { /* ... */ }, [])
// ❌ Not allowed: if (n > 0) useEffect(...)
// ❌ Not allowed: useState(0) inside a for loop
return <button onClick={() => setN(n + 1)}>{n}</button>
}
Returns:No return value; this is a coding pattern rather than a callable API.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
The panel lists two ✓ rules and one ✗ counter-example; clicking the buttons updates the count and the checkbox, and the Hooks keep running in the same fixed order no matter how you interact, so the state never gets crossed between slots.
💡 Key Points
⚠️ Warning Breaking a rule does not throw right away - you get strange bugs like "clicking button A changes the value of B"; eslint-plugin-react-hooks catches them before the build.
💡 Tip An early return must come after every Hook call, otherwise one render skips a Hook and shuffles the call order.
ℹ️ Info React Compiler can optimize components at build time, but the two rules remain the precondition for it to work.
🏷️ More Routing & State
💡 Related Cases
More case studies coming soon.
📚 Related Tutorials
❓ FAQ
Q Why can a Hook not be called inside a condition?
A React pairs each Hook with its state by call order; a conditional call makes the order drift and the n-th Hook ends up reading somebody else's state.
Q Can a custom Hook call other Hooks?
A Yes, that is exactly what a custom Hook is for - a function whose name starts with use follows the same top-level call rules inside its body.
Q Can a component return before calling its Hooks?
A No. Either move the Hooks above the return, or extract the JSX that comes after the return into a child component, so every Hook runs on every render.