Overview - Cleanup function
What is it?
In React, a cleanup function is a special function you write inside a component's effect to clean up or undo things when the component is about to change or disappear. It helps remove things like timers, subscriptions, or event listeners that you set up earlier. This keeps your app running smoothly without leftover tasks causing bugs or slowdowns. Think of it as tidying up after yourself when you leave a room.
Why it matters
Without cleanup functions, your app might keep running old tasks or listening to events even after you don't need them. This can cause bugs, memory leaks, or slow performance. Cleanup functions make sure your app stays fast and bug-free by removing what’s no longer needed. They help React components behave responsibly, especially when users navigate or data changes.
Where it fits
Before learning cleanup functions, you should understand React components and the useEffect hook, which runs code after rendering. After mastering cleanup functions, you can learn about advanced React patterns like custom hooks and performance optimization techniques.