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 and hands you somebody else's state.
So the order must be identical on every render. That is why hooks stay at the top level of the function, before any early return, and never inside an if, a loop, a try block or an event handler.
There are two rules in total. First, call hooks only at the top level. Second, call them only from function components or from other custom hooks, whose names start with use. Plain helper functions cannot call hooks.
Example
function Bad({ show }) {
if (show) {
const [n, setN] = useState(0); // hook order changes between renders: error
}
return null;
}
function Good({ show }) {
const [n, setN] = useState(0); // always called, same position
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 all hooks, and I keep the ESLint rule switched on."
Common mistakes
- Placing a hook after an early return.
- Calling a hook inside a loop or an event handler.