What is the difference between useEffect cleanup and componentWillUnmount?
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.
Previous
What is code splitting in React?
Next
What is memoization in React and how do you implement it?