Memory leaks in React functional components often happen when asynchronous operations (like fetch
, setTimeout
, or subscriptions) try to update state after a component has unmounted. This causes a warning and can eventually lead to memory issues.
🧯 How to Handle Memory Leaks in Functional Components
The key tool here is the useEffect
cleanup function. It runs when the component unmounts, or before the effect re-runs, letting you cancel timers, abort fetch requests, or unsubscribe from services.
✅ Example: Avoiding Memory Leak with fetch
🧠 Alternatives & Best Practices
-
AbortController for
fetch
:
-
Clear timers:
-
Unsubscribe from services (e.g., sockets, observers):
TL;DR
-
Use the
return
function inuseEffect
to clean up side effects. -
Prevent state updates on unmounted components using flags or cancellation tools.
-
Clean up timers, listeners, fetches, and subscriptions to prevent memory leaks.
Want an example with WebSockets or event listeners too?