Interview frequency: …
Short answer
Call Hooks only at the top level of a function (Top Level), and only from React component functions or Custom Hooks, so the internal state list remains in a stable order.
Explanation
React stores component state in a Linked List inside the Fiber Node, and relies only on the sequential order of Hook calls in every render to associate each Hook with its state. Putting a Hook in a condition (if) or loop can skip a call, shifting the pointer and mixing up state between Hooks.
Code example
// Wrong: calling inside a condition
if (isLoggedIn) {
useEffect(() => { ... }, []); // Will cause a fatal error
}
// Correct: call at the top level and put the condition inside the Hook
useEffect(() => {
if (isLoggedIn) {
// Conditional code inside the correct Hook
}
}, [isLoggedIn]);Common mistakes
- Calling useState from an ordinary helper function that is not a Custom Hook beginning with use.