Careeroza
Cleanup Function
Timer with Cleanup
Example
Return a function to stop timers, listeners or subscriptions. Without it, hiding the timer would leave the interval running (a memory leak).
import { useState, useEffect } from 'react';
function Timer() {
const [sec, setSec] = useState(0);
useEffect(() => {
const id = setInterval(() => setSec((s) => s + 1), 1000);
console.log('timer started');
return () => { clearInterval(id); console.log('timer cleaned up'); };
}, []);
return <p>Seconds: {sec}</p>;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} timer</button>
{show && <Timer />}
</div>
);
}Result