React: A lap timer with a ref for the interval

A timer started by a button needs to remember its interval id for the Stop button, but the id is never shown: a job for a ref.

What to build

A timer with Start, Stop and Lap buttons and a list of laps.

Requirements

  • Show the time in tenths of a second in a p with the id time (0.0 s at the start), ticking every 100 ms after Start.
  • Stop stops it; pressing Start again continues from the same time. Pressing Start while running does nothing extra.
  • Lap adds the current time to an ol with the id laps (each lap as N.N s).

Constraints

Store the interval id in a ref, not in state.

Example

Start, Lap after about 0.3 s, Stop: the list holds one lap of about 0.3 s.

Why it works

The interval id only matters to the buttons' handlers, so a ref keeps it without causing renders, while the time and the laps are state because they appear on the page.

Hints

Hint 1

Keep the interval id in a ref: intervalRef.current = setInterval(...).

Hint 2

Stop clears intervalRef.current; laps are state, because they are shown.

Solution

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

export default function App() {
  const [tenths, setTenths] = useState(0);
  const [laps, setLaps] = useState([]);
  const intervalRef = useRef(null);

  function start() {
    if (intervalRef.current !== null) return;
    intervalRef.current = setInterval(() => setTenths((t) => t + 1), 100);
  }

  function stop() {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  }

  return (
    <div>
      <p id="time">{(tenths / 10).toFixed(1)} s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
      <button onClick={() => setLaps([...laps, (tenths / 10).toFixed(1) + " s"])}>Lap</button>
      <ol id="laps">
        {laps.map((lap, i) => (
          <li key={i}>{lap}</li>
        ))}
      </ol>
    </div>
  );
}

Lesson: Refs: remembering without rendering →