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
This guide is brought to you by DodaTech — built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
How to Fix React Mount Lifecycle Issues
Next →
How to Fix React Update Lifecycle Re-render Issues
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro