React Mastery / React Hooks

useEffect with Cleanup

🧹 Cleanup Function in useEffect

  • A cleanup function is used to remove or stop side effects created inside useEffect.

  • It helps prevent memory leaks and unwanted behavior.

  • The cleanup function is returned from the useEffect callback.


🔄 When Does Cleanup Run?

  • Before the component unmounts

  • Before the effect runs again (when dependencies change)


✍️ Syntax

useEffect(() => {
  // setup side effect

  return () => {
    // cleanup logic
  };
}, [dependencies]);

✅ Common Use Cases

  • Clearing timers (setInterval, setTimeout)

  • Removing event listeners

  • Cancelling API subscriptions

  • Stopping observers or sockets


🧪 Simple Example

🧠 Explanation:

  • Timer starts when component mounts

  • Timer stops when component unmounts

  • Prevents background execution


🔁 Class Component Equivalent

Class Component

useEffect

componentWillUnmount()

Cleanup function


⭐ Key Points

  • Cleanup is optional, but important

  • Always clean up timers, listeners, subscriptions

  • One useEffect = one cleanup function


🔚 In Short

Cleanup function = undo what your effect did