What are the rules of hooks, and why do they exist?
Call hooks only at the top level of a component or custom hook, never inside loops, conditions or nested functions, and only from React functions. React tracks hooks by call order, so the order must be the same every render.
Explain it simply
React does not know your hooks by name. It remembers them by position: first hook, second hook, third hook. It is like lockers numbered 1, 2, 3 in a college hostel. If a condition skips one call, every later hook opens the wrong locker.
So the order must be identical on every render. That is why hooks stay at the top level, before any early return.
Example
function Bad({ show }) {
if (show) {
const [n, setN] = useState(0); // hook order changes: error
}
return null;
}
function Good({ show }) {
const [n, setN] = useState(0); // always called
if (!show) return null;
return <p>{n}</p>;
}The ESLint plugin eslint-plugin-react-hooks flags these mistakes automatically.
What to say in the interview
"Hooks must be called at the top level, in the same order on every render, and only from function components or custom hooks. React identifies each hook by its call index, so a conditional call shifts the order and corrupts state. I put conditions inside the hook or after the hooks, and I keep the ESLint rule on."
Common mistakes
- Placing a hook after an early return.
- Calling a hook inside a loop or an event handler.