#atom

Subtitle:

Essential placement rule for React Hooks to maintain stable render order


Core Idea:

React Hooks must be called at the top level of a component or custom Hook, never inside loops, conditions, nested functions, or try/catch blocks to ensure consistent ordering between renders.


Key Principles:

  1. Consistent Execution Order:
    • React relies on the order of Hook calls to associate state with the correct Hook.
  2. Unconditional Invocation:
    • Hooks must execute in the same order on every render to maintain state correlation.
  3. Early Return Consideration:
    • Hooks should be called before any conditional return statements.

Why It Matters:


How to Implement:

  1. Place Hooks First:
    • Call all Hooks at the beginning of the component body
  2. Move Conditions Inside Hooks:
    • Use conditions inside Hook effects rather than wrapping Hook calls in conditions
  3. Extract Logic to Custom Hooks:
    • If conditional Hook logic is needed, move it into a custom Hook

Example:

// 🔴 Incorrect: Hook inside condition
function ProfilePage({ userId }) {
  if (userId) {
    const [user, setUser] = useState(null);
    // This breaks the rules
  }
  // ...
}

// ✅ Correct: Hook at top level with conditional logic inside
function ProfilePage({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    if (userId) {
      fetchUser(userId).then(userData => setUser(userData));
    }
  }, [userId]);
  // ...
}
    ```
    
- **Result**:
    - The component correctly maintains state association across renders while implementing conditional logic

---

### **Connections**:

- **Related Concepts**:
    - Rules of Hooks: Parent concept containing all Hook rules
    - useEffect Dependencies: How to properly manage effect dependencies
- **Broader Concepts**:
    - React Rendering Logic: How React processes and renders components
    - Component Lifecycle: How components initialize, update, and clean up

---

### **References**:

1. **Primary Source**:
    - React Official Documentation - Rules of Hooks
2. **Additional Resources**:
    - "A Complete Guide to useEffect" by Dan Abramov

---

### **Tags**:

#react #hooks #component-design #state-management #error-prevention

---
**Connections:**
- 
---
**Sources:**
- From: Rules of Hooks – React