Skip to content

How to Fix React Unmount Lifecycle Cleanup

DodaTech Updated 2026-06-26 1 min read

The Problem

In this quick-fix, you'll learn how to handle unmount cleanup for timers subscriptions async ops. This matters because failing to clean up causes memory leaks and console errors. In real-world applications, this pattern appears in real-time chat components live dashboards media players.

The Wrong Way

function WeatherWidget({ city }) {
  const [weather, setWeather] = useState(null);
  useEffect(() => {
    fetch('/api/weather/' + city).then(r=>r.json()).then(setWeather);
  }, [city]);
  return <div>{weather?.temp}C</div>;
}
Warning: state update on unmounted component if unmount happens before fetch

The Right Way

function WeatherWidget({ city }) {
  const [weather, setWeather] = useState(null);
  useEffect(() => {
    const controller = new AbortController();
    fetch('/api/weather/' + city, {signal: controller.signal})
      .then(r=>r.json()).then(setWeather)
      .catch(e => { if(e.name !== 'AbortError') console.error(e); });
    return () => controller.abort();
  }, [city]);
  return <div>{weather?.temp}C</div>;
}
On unmount fetch cancelled -- no warning no leak

Prevention

  • Clean up async operations in useEffect return
  • Use AbortController for fetch
  • Use boolean flag for non-cancelable ops
  • Clear timers in cleanup

FAQ

### How to test unmount behavior??

const { unmount } = render(); unmount(); Verify timers cleared subscriptions cancelled.

Does cleanup run when deps change??

Yes. React runs cleanup from previous render then runs new effect. Ensures old subscriptions torn down before new ones.

What if I forget cleanup??

First render works but subsequent renders and unmounts leak resources. Accumulated leaks degrade performance over time.

This guide is brought to you by DodaTech — built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro