All topics
Hooksbeginner

Rules of Hooks

Understand the two rules that govern how hooks must be called, and why they exist.

React hooks come with two non-negotiable rules: only call hooks at the top level of a function component or custom hook (never inside loops, conditions, or nested functions), and only call hooks from React function components or other custom hooks (never from plain JavaScript functions or class components).

Hooks are like items announced in a fixed-order roll call — the teacher (React) matches responses purely by the order names are called, not by who's speaking, so if someone is skipped one day, every subsequent name gets checked off against the wrong response.

Key Concepts

1
These rules exist because React tracks hook state by the *order* in which hooks are called during a render, not by name or any explicit identifier. Each useState, useEffect, etc. call corresponds to a slot in a linked list attached to the component's fiber, matched purely by call sequence. If a hook call is skipped conditionally on one render but present on another, every subsequent hook's slot shifts, corrupting state association.
useStateuseEffect
2
The eslint-plugin-react-hooks package's rules-of-hooks rule statically enforces this by flaging hooks called inside if statements, loops, or after early returns, catching violations before they become confusing runtime bugs. This linting is considered essential in any serious React codebase, not an optional nicety.
eslint-plugin-react-hooksrules-of-hooksif
3
Interviewers commonly present a snippet with a hook called conditionally (e.g., if (isLoggedIn) { useEffect(...) }) and ask candidates to explain precisely why it breaks, expecting an answer about call-order-based state association rather than a vague 'React doesn't like that.'
if (isLoggedIn) { useEffect(...) }