SmartCodingTips

๐Ÿงน Cleanup in useEffect()

In React, cleanup functions inside useEffect() help prevent memory leaks by removing subscriptions, timers, or listeners when a component unmounts or re-renders.


โ— Why Cleanup Is Important

  • Prevents memory leaks in long-running applications
  • Clears timers, intervals, and subscriptions
  • Avoids unwanted behavior like duplicated event listeners

๐Ÿ•’ Example: setInterval Cleanup

import React, { useState, useEffect } from "react";

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount(prev => prev + 1);
    }, 1000);

    return () => {
      clearInterval(timer); // ๐Ÿ” Clean up the interval
    };
  }, []);

  return <p>Seconds: {count}</p>;
}

Without cleanup, the interval would continue even after the component is removed from the DOM.

๐Ÿ–ฑ๏ธ Example: Event Listener Cleanup

useEffect(() => {
  function handleResize() {
    console.log("Window resized");
  }

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize); // โŒ Prevent multiple listeners
  };
}, []);

Always clean up event listeners to avoid multiple identical callbacks running.

๐Ÿ“… When Does Cleanup Run?

  • When the component unmounts (like navigating away)
  • Before running a new effect (if dependencies change)

โœ… Summary

  • Return a function inside useEffect() to handle cleanup
  • Useful for intervals, subscriptions, event listeners
  • Improves performance and stability of your app