Rules of Hooks
React hooks must follow two essential rules: only call hooks at the top level (never inside loops, conditions, or nested functions), and only call hooks from React function components or custom hooks.
These rules ensure React can correctly associate state between renders, since hooks rely on consistent call order.
Rule 1: Top level only
Never call hooks inside if statements, loops, or nested functions โ always call them at the top level of the component so their order stays consistent every render.
Rule 2: Only from React functions
Call hooks only from function components or other custom hooks, not from regular JavaScript functions or class components.
// โ Wrong: conditional hook call
function Bad({ show }) {
if (show) {
const [x, setX] = useState(0); // breaks call order
}
return null;
}
// โ
Correct
function Good({ show }) {
const [x, setX] = useState(0);
if (!show) return null;
return <p>{x}</p>;
}(Good renders correctly, Bad violates hook rules)Hooks must always run in the same order on every render.
Key points
- Only call hooks at the top level, never in conditions or loops.
- Only call hooks from function components or custom hooks.
- React relies on consistent call order to track state per hook.
- The eslint-plugin-react-hooks plugin catches most violations automatically.
