You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
import{useState,useRef}from"react";exportdefaultfunctionStopwatch(){conststartTime=useRef(null);constnow=useRef(null);const[secondPassed,setSecondPassed]=useState(0);constintervalRef=useRef(null);functionhandleStart(){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);}functionhandleStop(){clearInterval(intervalRef.current);}return(<><h1>Hi, Time passed: {secondPassed.toFixed(3)}</h1><buttononClick={handleStart}>Start</button><buttononClick={handleStop}>Stop</button></>);}
The text was updated successfully, but these errors were encountered:
Summary
In the code sample of StopWatch, the DOM's re-rendering only depends on
secondsPassed
.now
andstartTime
are just used for calculation. If they are treated asstate
, 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:
now
andstartTime
asref
secondPassed
asstate
The text was updated successfully, but these errors were encountered: