A cleanup function helps remove or undo things when a component stops showing on the screen. It keeps your app tidy and avoids problems like memory leaks.
0
0
Cleanup function in React
Introduction
When you start a timer or interval and want to stop it when the component is gone.
When you add event listeners and want to remove them to avoid errors.
When you open a connection or subscription and want to close it to save resources.
When you want to reset or clear data when a component unmounts or updates.
Syntax
React
useEffect(() => {
// setup code here
return () => {
// cleanup code here
};
}, [dependencies]);The cleanup function is the function returned inside useEffect.
It runs before the component unmounts or before the effect runs again if dependencies change.
Examples
This example sets a timer and clears it when the component unmounts to avoid running code after it's gone.
React
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer done');
}, 1000);
return () => {
clearTimeout(timer);
};
}, []);This example adds a window resize listener and removes it when the component unmounts to keep things clean.
React
useEffect(() => {
function onResize() {
console.log('Window resized');
}
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, []);Sample Program
This component counts up every second. When it is removed from the screen, the cleanup function stops the counting interval and logs a message.
React
import React, { useState, useEffect } from 'react'; function TimerComponent() { const [count, setCount] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setCount(c => c + 1); }, 1000); return () => { clearInterval(intervalId); console.log('Interval cleared'); }; }, []); return ( <div> <p>Count: {count}</p> </div> ); } export default TimerComponent;
OutputSuccess
Important Notes
Always use cleanup functions to avoid memory leaks and unexpected behavior.
Cleanup runs before the next effect if dependencies change, so it helps reset things properly.
Summary
Cleanup functions run when a component unmounts or before effects rerun.
They help remove timers, listeners, or subscriptions to keep apps healthy.
Use them inside useEffect by returning a function.