A Cleanup Function is a function inside useEffect that cleans up or stops previous operations when they are no longer needed.
Cleanup function helps us stop timers, remove event listeners and avoid unnecessary operations.
Syntax
useEffect(() => {
return () => {
};
}, []);
Here, return () => {} is the cleanup function.
When does Cleanup Function run?
There are 3 important situations:
Unmounting: When a component is removed from the screen.
Updating dependencies: Before the effect runs again because a dependency changed.
Development Strict Mode: React may run an extra setup and cleanup cycle to check your effect.
Example:
setInterval
import { useEffect } from 'react';
function App() {
useEffect(() => { const timer = setInterval(() => { console.log("Hello React"); }, 1000); return () => { clearInterval(timer); console.log("Timer Stopped"); }; }, []); return <h1>Hello!</h1>; }
export default App;
Step-by-step explanation:
- Component mounts.
- useEffect runs.
- setInterval starts.
- Every 1 second, "Hello React" prints.
- Component unmounts.
- Cleanup function runs.
clearInterval(timer) stops the timer.
Example:
Event Listener:
useEffect(() => {
function handleClick() { console.log("Clicked!"); } window.addEventListener("click", handleClick); return () => { window.removeEventListener("click", handleClick); }; }, []);
Why cleanup?
Without cleanup, the event listener may remain active even after the component is removed.
