Intermediate LevelReact JS & React 19
How do you identify and fix memory leaks from unmounted React components?
❓ Interview Prompt: Explain component unmounting memory leaks, uncleared timers, lingering WebSocket subscriptions, and `AbortController` fetch cancellation.
Memory leaks occur when unmounted components leave active background tasks (timers, event listeners, API requests) running, which attempt to update state on unmounted components:
3 Prevention Patterns:
1
Timers: Clear 'setTimeout'/'setInterval' handles in 'useEffect' cleanup.
2
Network Requests: Pass 'AbortController.signal' to 'fetch()' calls and call 'controller.abort()' on cleanup.
3
Event Listeners: Call 'removeEventListener' on cleanup.
Code Implementation Example
jsx
function UserFetcher({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const controller = new AbortController(); // 1. Create AbortController
fetch('/api/users/${userId}', { signal: controller.signal })
.then(res => res.json())
.then(data => setUser(data))
.catch(err => {
if (err.name !== 'AbortError') console.error(err);
});
// 2. Abort pending fetch network call if component unmounts!
return () => controller.abort();
}, [userId]);
}💡Canceling pending fetch network requests on unmount using AbortController.
🎯 Interview Key Takeaway
Always cancel pending fetch requests with AbortController and clear timers in useEffect cleanup functions to prevent memory leaks.
#Memory Leaks#AbortController#Cleanup#Intermediate
Back to all React JS & React 19 Questions→