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
pwith the idtime(0.0 sat the start), ticking every 100 ms afterStart. Stopstops it; pressingStartagain continues from the same time. PressingStartwhile running does nothing extra.Lapadds the current time to anolwith the idlaps(each lap asN.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>
);
}