React Hooks
React Rules of Hooks
There are two rules. Call hooks only at the top level of a component or another hook — never inside conditions, loops or nested functions. And call them only from React function components or custom hooks, never from ordinary functions or class methods.
What is Rules of Hooks in React?
There are two rules. Call hooks only at the top level of a component or another hook — never inside conditions, loops or nested functions. And call them only from React function components or custom hooks, never from ordinary functions or class methods.
Why Rules of Hooks matters
React has no names for your hooks; it identifies them purely by the order in which they are called. Skip one call on a later render and every subsequent hook receives the wrong slot.
Rules of Hooks example
// WRONG — the hook order changes when isOpen flips
function Panel({ isOpen }) {
if (isOpen) {
const [height, setHeight] = useState(0); // ❌
}
const [tab, setTab] = useState('info');
}
// RIGHT — always call, branch on the value instead
function Panel({ isOpen }) {
const [height, setHeight] = useState(0);
const [tab, setTab] = useState('info');
if (!isOpen) return null;
}How this works
In the first version React stores [height] as hook #1 when the panel is open, but useState('info') claims slot #1 when it is closed. The stored values are handed to the wrong variables, and React throws "Rendered fewer hooks than expected".
Key points to remember
- Hooks at the top level, every render, in the same order.
- Early returns must come after every hook call.
- Install eslint-plugin-react-hooks — it catches both violations automatically.
Common mistakes with Rules of Hooks
- A conditional hook that only breaks once a user toggles something in production.
- Calling a hook inside a map callback or an event handler.
- Disabling the exhaustive-deps lint rule instead of fixing the dependency.
React Rules of Hooks— Interview Questions & FAQs
Why can I not call hooks conditionally?+
React tracks hooks by call order, not by name. A conditional call shifts every later hook to a different slot, so values leak between them and React throws "Rendered fewer hooks than expected".
