Digiaru

Digiaru started this conversation 3 months ago.

Memory Leak or “setState on unmounted component” warning in useEffect

While fetching data in useEffect, I sometimes get this warning: "Can't perform a React state update on an unmounted component. This is a no op, but it indicates a memory leak..." I think it's due to calling setState after the component unmounted.

Kar

Posted 3 months ago

The warning occurs when asynchronous logic continues after the component unmounts—then updates state unexpectedly. This often happens with API calls or subscriptions in useEffect lacking cleanup logic. Fix ✅: Use a cancel flag or cancel tokens to ensure state updates only when the component is still mounted: js Copy code useEffect(() => { let isMounted = true; api.fetchData().then(data => { if (isMounted) setData(data); }); return () => { isMounted = false }; }, []); For fetch/axios, prefer AbortController or cancel token methods in cleanup.