Q8: What are the Rules of Hooks and why are they enforced?

  1. Only call Hooks at the Top Level: Don't call Hooks inside loops, conditions, or nested functions.
  2. Only call Hooks from React Functions: Call Hooks from Functional Components or Custom Hooks. Enforced because React relies on the exact execution order of Hooks across re-renders to map state variables to internal Fiber linked list nodes.
Rules of Hooks Violation vs Correct Pattern
// ❌ BAD: Conditional Hook call alters Hook execution order
if (isLoggedIn) {
  useEffect(() => fetchUserData(), []);
}

// ✅ GOOD: Keep Hook top-level, move condition inside Hook
useEffect(() => {
  if (isLoggedIn) {
    fetchUserData();
  }
}, [isLoggedIn]);
💡 Keeping useEffect at the top level guarantees that Hook index pointers match internal Fiber node linked lists.
Key Takeaways
  • React tracks Hook states using an ordered linked list on the Fiber node.
  • Conditional Hook calls alter execution order, mismatching state bindings.
Knowledge Check

Why does calling a Hook inside an IF statement break React applications?