React: A stopwatch with a cleaned-up interval

An interval that starts and stops with state is the classic effect with cleanup.

What to build

A stopwatch with Start, Stop and Reset buttons.

Requirements

  • Show the time in a p with the id time as seconds with one decimal and s, starting at 0.0 s, counting tenths of a second.
  • Buttons Start, Stop and Reset: Start makes the time run, Stop freezes it, Reset stops it and sets it to 0.0 s.
  • Use an effect that depends on whether the stopwatch is running, and clears its interval in its cleanup.

Constraints

Count with setInterval every 100 ms.

Example

Start, wait about half a second, Stop: the time shows about 0.5 s and stays there.

Why it works

While running is true the effect keeps one interval going; when it becomes false React runs the cleanup, which clears it, so there is never a stray timer.

Hints

Hint 1

Keep running and tenths in state; an effect that depends on running starts an interval only while it is true.

Hint 2

The effect's cleanup clears the interval, which runs when running changes or the component goes away.

Solution

Show one correct solution (try it yourself first)
import { useEffect, useState } from "react";

export default function App() {
  const [tenths, setTenths] = useState(0);
  const [running, setRunning] = useState(false);

  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => setTenths((t) => t + 1), 100);
    return () => clearInterval(id);
  }, [running]);

  return (
    <div>
      <p id="time">{(tenths / 10).toFixed(1)} s</p>
      <button onClick={() => setRunning(true)}>Start</button>
      <button onClick={() => setRunning(false)}>Stop</button>
      <button
        onClick={() => {
          setRunning(false);
          setTenths(0);
        }}
      >
        Reset
      </button>
    </div>
  );
}

Lesson: Effects: syncing with the outside world →