Open
Description
Summary
In the code sample of StopWatch, the DOM's re-rendering only depends on secondsPassed
. now
and startTime
are just used for calculation. If they are treated as state
, then very change on them will cause the re-rendering. Am I right?
Page
https://react.dev/learn/referencing-values-with-refs
Details
My suggestion is:
- define
now
andstartTime
asref
- define
secondPassed
asstate
import { useState, useRef } from "react";
export default function Stopwatch() {
const startTime = useRef(null);
const now = useRef(null);
const [secondPassed, setSecondPassed] = useState(0);
const intervalRef = useRef(null);
function handleStart() {
startTime.current = Date.now();
now.current = Date.now();
clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
now.current = Date.now();
if (startTime != null && now != null) {
setSecondPassed((now.current - startTime.current) / 1000);
}
}, 10);
}
function handleStop() {
clearInterval(intervalRef.current);
}
return (
<>
<h1>Hi, Time passed: {secondPassed.toFixed(3)}</h1>
<button onClick={handleStart}>Start</button>
<button onClick={handleStop}>Stop</button>
</>
);
}