// src/App.jsx
import { useEffect, useState } from "react";
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return
Elapsed: {seconds}s
;
}
function App() {
return ;
}
export default App;
/*
Notes:
- The functional update form (prev => prev + 1) is used inside the
interval callback rather than referencing seconds directly, since
the callback was created once when the effect first ran and would
otherwise always see that original value.
- The cleanup function (return () => clearInterval(id)) runs when
the component unmounts, stopping the interval so it doesn't keep
running in the background forever.
*/