- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Effect Cleanup
Effects and Refs
Effect Cleanup
Whatever an effect starts, its cleanup must stop. React runs cleanup before the next effect and again when the component unmounts.
Returning a cleanup function
If an effect returns a function, React calls it before running the effect again and when the component leaves the tree. Anything ongoing - a timer, a listener, a subscription - needs one.
A timer that stops
jsx
function Ticker() {
const [seconds, setSeconds] = React.useState(0)
React.useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000)
// Without this, the interval keeps firing after unmount.
return () => clearInterval(id)
}, [])
return <p>Running for {seconds}s</p>
}
function Demo() {
const [show, setShow] = React.useState(true)
return (
<div>
<button onClick={() => setShow((s) => !s)}>{show ? "Unmount" : "Mount"} the ticker</button>
{show && <Ticker />}
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Demo />)