Skip to content

Cleaning Up

The Course
•
20 min study

On Day 3 you built a study timer that only counted the minutes you logged by hand. This one keeps real time, with setInterval. Starting the interval is an effect. Stopping it is that effect's cleanup.

A timer that cleans up React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; export default function App() { const [seconds, setSeconds] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { if (!running) return; console.log("Starting a timer"); const id = setInterval(() => { setSeconds((s) => s + 1); }, 1000); return () => { console.log("Stopping a timer"); clearInterval(id); }; }, [running]); return ( <main> <h1>{seconds} seconds</h1> <button onClick={() => setRunning(!running)}>{running ? "Pause" : "Start"}</button>{" "} <button onClick={() => setSeconds(0)}>Reset</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Start, wait a few seconds, then Pause, Start, Pause. Watch the console.

The cleanup function

JavaScript
useEffect(() => {
  if (!running) return;
  const id = setInterval(() => {
    setSeconds((s) => s + 1);
  }, 1000);
  return () => clearInterval(id);
}, [running]);

The function an effect returns is its cleanup. React calls it:

  • before running the effect again, because a dependency changed, and
  • when the component leaves the screen.

So every Starting a timer is followed by a Stopping a timer before the next one starts. There's never more than one interval.

Two more details:

  • When running is false, the effect returns early with no interval and no cleanup. That's fine.
  • setSeconds((s) => s + 1) uses an updater function. The interval keeps calling the same arrow function, which belongs to the render that started it. Its seconds would be stuck at that render's value, but s is always the latest one.

Predict: no cleanup

Delete the return () => { ... }; block, leaving the interval running forever. Run, then press Start, Pause, Start. Predict how fast the seconds go up now.

Check your prediction

Two seconds per second, and Pause no longer stops it. Each Start makes a new interval, and nothing ever clears the old ones. In a real app, leaks like this pile up: timers, subscriptions and requests that outlive the component that started them. Put the cleanup back, and press Run to clear the extra timers.

Your turn

Exercise

A fast mode

Add a button that switches the timer between normal speed, one tick every 1000 ms, and fast speed, one tick every 250 ms. It reads Fast at normal speed and Normal at fast speed.

Switching while the timer runs must change the speed straight away. The console must show one Stopping a timer followed by one Starting a timer, so there is never more than one interval. Switching while paused must not start the timer.

Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; export default function App() { const [seconds, setSeconds] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { if (!running) return; console.log("Starting a timer"); const id = setInterval(() => { setSeconds((s) => s + 1); }, 1000); return () => { console.log("Stopping a timer"); clearInterval(id); }; }, [running]); return ( <main> <h1>{seconds} seconds</h1> <button onClick={() => setRunning(!running)}>{running ? "Pause" : "Start"}</button>{" "} <button onClick={() => setSeconds(0)}>Reset</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The interval's delay is now a value the effect reads. When it changes, the old interval has to stop and a new one start, at the new speed. Cleanup and the dependency list already do exactly that when running changes.

Hint 2: a first step

Add a fast state that starts as false, a button that flips it, and use fast ? 250 : 1000 as the interval's delay. Press Start, then Fast: the seconds still go up once a second, and the console shows no new lines. The effect didn't run again. What does React check to decide whether it should?

Show one solution
JavaScript
const [fast, setFast] = useState(false);

useEffect(() => {
  if (!running) return;
  console.log("Starting a timer");
  const id = setInterval(() => {
    setSeconds((s) => s + 1);
  }, fast ? 250 : 1000);
  return () => {
    console.log("Stopping a timer");
    clearInterval(id);
  };
}, [running, fast]);
JSX
<button onClick={() => setFast(!fast)}>{fast ? "Normal" : "Fast"}</button>

fast is read inside the effect, so it goes in the dependency list. When it changes, React runs the cleanup, which clears the old interval, and then the effect, which starts one at the new speed. While paused, the effect returns early, so switching speed only changes what the next Start will use.

Was this article helpful?

Your response is saved on this device.