React·Intermediate·Coding·1 min read
Why must Hooks be called in the same order?
Short interview answer
React associates hook state with call positions in a component's render. Calling hooks conditionally or in loops can shift those positions between renders and attach state to the wrong hook. Hooks therefore run at the top level of components or custom hooks.
Example
// Breaks the call-order guarantee:if (isLoggedIn) { const [name, setName] = useState('');}
// Correct: hook is unconditional, the branch is insideconst [name, setName] = useState('');if (isLoggedIn) { /* use name */ }Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.