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:
- Component Context Requirement:
- Hooks are designed to work within React's rendering and lifecycle system.
- Custom Hook Pattern:
- Custom Hooks (functions starting with "use") are the only non-component functions that should call Hooks.
- Event Handler Limitations:
- Hooks cannot be called inside event handlers or other callback functions.
Why It Matters:
- Rendering Integration:
- Hooks depend on React's internal rendering mechanisms to function properly.
- State Consistency:
- Calling Hooks from inappropriate contexts breaks React's ability to track state changes.
- Component Architecture:
- This rule enforces clean separation of stateful logic within the component hierarchy.
How to Implement:
- Use Function Components:
- Convert class components to function components when Hooks are needed
- Create Custom Hooks:
- Extract reusable Hook logic into dedicated functions with "use" prefix
- Keep State Updates in Rendering Context:
- Move state-dependent logic from event handlers into the main component body or effects
Example:
- Scenario:
- Creating reusable authentication logic across multiple components
- Application:
// ✅ 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