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
pwith the idtimeas seconds with one decimal ands, starting at0.0 s, counting tenths of a second. - Buttons
Start,StopandReset: Start makes the time run, Stop freezes it, Reset stops it and sets it to0.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>
);
}