Cleanup in Effects
7 min read
Preventing Memory Leaks and Stale Effects
Effects can return a cleanup function that React calls before re-running the effect or when the component unmounts. Use cleanup to cancel subscriptions, clear timers, abort fetch requests, and remove event listeners.
jsx
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
// Cleanup: remove the listener when the component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array: register once, clean up on unmount
return width;
}In React 18 Strict Mode, effects mount → unmount → remount in development to surface missing cleanup functions. If your effect breaks during remount, you need a cleanup function.
Ready to test yourself?
Practice React— quiz & coding exercises