#atom

Subtitle:

Restriction on Hook calling contexts to maintain React's component model


Core Idea:

React Hooks can only be called from React function components or custom Hooks, never from regular JavaScript functions, class components, or outside the React rendering cycle.


Key Principles:

  1. Component Context Requirement:
    • Hooks are designed to work within React's rendering and lifecycle system.
  2. Custom Hook Pattern:
    • Custom Hooks (functions starting with "use") are the only non-component functions that should call Hooks.
  3. Event Handler Limitations:
    • Hooks cannot be called inside event handlers or other callback functions.

Why It Matters:


How to Implement:

  1. Use Function Components:
    • Convert class components to function components when Hooks are needed
  2. Create Custom Hooks:
    • Extract reusable Hook logic into dedicated functions with "use" prefix
  3. Keep State Updates in Rendering Context:
    • Move state-dependent logic from event handlers into the main component body or effects

Example:

// ✅ Correct: Custom Hook definition
function useAuthentication() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const checkAuth = async () => {
      setLoading(true);
      const currentUser = await checkUserSession();
      setUser(currentUser);
      setLoading(false);
    };
    
    checkAuth();
  }, []);
  
  return { user, loading };
}

// ✅ Correct: Using the Hook in a component
function ProfilePage() {
  const { user, loading } = useAuthentication();
  
  if (loading) return <LoadingSpinner />;
  if (!user) return <LoginPrompt />;
  
  return <UserProfile userData={user} />;
}

// 🔴 Incorrect: Calling Hooks in regular function
function getUser() {
  // This breaks the rules
  const [user, setUser] = useState(null);
  return user;
}    ```
    
- **Result**:
    - Authentication logic is properly encapsulated in a custom Hook that can be shared across components

---

### **Connections**:

- **Related Concepts**:
    - Rules of Hooks: Parent concept containing all Hook rules
    - Custom Hooks: Pattern for reusing Hook logic between components
- **Broader Concepts**:
    - Component Composition: Strategies for combining components
    - Higher-Order Components vs Hooks: Different patterns for code reuse

---

### **References**:

1. **Primary Source**:
    - React Official Documentation - Rules of Hooks
2. **Additional Resources**:
    - "Building Your Own Hooks" - React documentation

---

### **Tags**:

#react #hooks #custom-hooks #component-architecture #code-reuse

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