Effect Cleanup
Effect cleanup is work that stops an effect when it is no longer needed. It stops a timer when the component leaves the page.
Starting a timer
The effect starts a timer that ticks each second.
useEffect(() => {
const timer = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
}, []);Returning the cleanup
The returned function stops the timer.
useEffect(() => {
const t = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(t);
}, []);Cleanup on leaving
React runs the returned function when the component leaves the page.
return () => clearInterval(timer);Example
import { useState, useEffect } from 'react';
export default function App() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Seconds: {seconds}</p>;
}
Key points
- Some effects start work that keeps running.
- A timer is one example of work that keeps running.
- Cleanup is a function that stops that work.
- React runs cleanup when the component leaves the page.
In this example, the component calls useState at the top. The call makes a count of seconds that starts at zero. The effect starts a timer that adds one each second. The effect returns a function that clears the timer. The returned function is the cleanup. The first render shows zero seconds before the timer ticks.
Note
An effect that starts a timer should return its cleanup.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the cleanup function do in the timer example?