What if your app could clean up after itself perfectly every time you leave a screen?
Why Cleanup function in React? - Purpose & Use Cases
Imagine you add event listeners or timers in your React component, but forget to remove them when the component disappears from the screen.
This can cause your app to slow down or behave strangely over time.
Manually tracking and removing these side effects is tricky and easy to forget.
It leads to memory leaks, unexpected bugs, and poor user experience.
React's cleanup function lets you neatly remove side effects when a component unmounts or before it updates.
This keeps your app fast, clean, and bug-free without extra hassle.
useEffect(() => {
window.addEventListener('resize', handleResize);
// forgot to remove listener
});useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);You can safely add timers, listeners, or subscriptions knowing React will clean them up automatically.
When building a chat app, cleanup functions help remove WebSocket connections when you leave a chat room, preventing unwanted messages and saving resources.
Manual cleanup is error-prone and causes bugs.
React cleanup functions run automatically at the right time.
This keeps your app efficient and reliable.