Skip to content
Justice Tech School

Project: Stopwatch

Use state, effect and cleanup.

Example
function Stopwatch() {
  const [s, setS] = useState(0);
  const [run, setRun] = useState(false);
  useEffect(() => {
    if (!run) return;
    const id = setInterval(() => setS((x) => x + 1), 1000);
    return () => clearInterval(id);
  }, [run]);
  return <button onClick={() => setRun(!run)}>{s}s</button>;
}

Exercise

Stop the timer.

return () => (id);

Quiz Test

Why clean up the interval?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.