SmartCodingTips

πŸ“ 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