What is the difference between useEffect cleanup and componentWillUnmount?
Why Interviewers Ask This
Mid-level React.js roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
Both handle cleanup when a component is unmounted, but useEffect cleanup is more powerful. componentWillUnmount: called once, just before the component is removed from the DOM. Only fires on unmount. useEffect cleanup: runs before the component unmounts AND before the effect re-runs (on every dependency change). This is a key difference: useEffect(() => { const sub = subscribe(id); return () => sub.unsubscribe(); }, [id]); — when id changes, the cleanup runs first (unsubscribes the old subscription), then the effect runs again (subscribes with the new id). With componentWillUnmount, you would need componentDidUpdate to handle the subscription change. useEffect cleanup handles both cases with one mechanism. Common cleanup tasks: cancel fetch requests (AbortController), clear timeouts/intervals, unsubscribe from observables/events, remove DOM event listeners, disconnect ResizeObserver/IntersectionObserver, close WebSocket connections. React 18 Strict Mode: cleanup + re-run happens once in development to verify cleanup is correct — this is intentional and reveals missing cleanup bugs.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last React.js project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is code splitting in React?
Next
What is memoization in React and how do you implement it?