π Hook Rules & Best Practices
React Hooks are powerful, but they come with important rules and recommended practices to avoid bugs and ensure consistent behavior.
π Rules of Hooks
- Only call Hooks at the top level: Donβt call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React functions: They should only be used inside function components or custom hooks.
// β
Correct
function MyComponent() {
const [count, setCount] = useState(0);
}
// β Incorrect
if (condition) {
const [value, setValue] = useState(0); // Donβt do this
}
β Best Practices
1. Keep Hook dependencies accurate
Always include all external values used in useEffect
inside its dependency array.
// β
Correct
useEffect(() => {
console.log(user.name);
}, [user]);
2. Use multiple Hooks for separation
Donβt cram everything into one effect or state. Separate logic using multiple hooks.
// Better structure
useEffect(() => { fetchData(); }, []);
useEffect(() => { listenToScroll(); }, []);
3. Extract reusable logic into custom hooks
Encapsulate shared logic across components into custom hooks for readability and reuse.
// Example
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
const handleStatus = () => setIsOnline(navigator.onLine);
window.addEventListener('online', handleStatus);
window.addEventListener('offline', handleStatus);
return () => {
window.removeEventListener('online', handleStatus);
window.removeEventListener('offline', handleStatus);
};
}, []);
return isOnline;
}
4. Avoid unnecessary state
Donβt use state when a derived value can be calculated directly from props or other state.
// β Donβt store derived state
const [total, setTotal] = useState(price * quantity);
// β
Derive it directly
const total = price * quantity;
5. Clean up after side effects
Always return a cleanup function from useEffect
when working with subscriptions, timers, etc.
π§ Summary
- Follow the 2 official rules of Hooks
- Keep effects and logic separate
- Use custom hooks for reuse
- Minimize and clean up side effects
- Keep dependencies correct to avoid bugs