title: React useState value sets to the previous value after setting to a new value
body: <p>When 1 min passes, <code>min</code> (a minute variable) is calculated and if it is more than 0 (which means that at least 60 secs or 1 min passed) <code>m</code> (also a minute variable but uses useState to display minutes on stopwatch display) sets to &quot;1:&quot; (1 minute passed) or &quot;2:&quot; and so on. When I reset the stopwatch <code>m</code> sets to empty string &quot;&quot; and stopwatch display no minutes, 00 sec and 00 ms. But when I start it again, instead of &quot;&quot; <code>m</code> shows the previous value (&quot;1:&quot; if it was &quot;1:&quot; before the reset).</p>
  <pre><code>const [isPlaying, setIsPlaying] = useState(false)
  const [startTime, setStartTime] = useState(Date.now())
  const [elapsedTime, setElapsedTime] = useState(0)
  const [stopTime, setStopTime] = useState(0)
  const [time, setTime] = useState(null)
  let sec, msec, min
  const [s, setS] = useState(&quot;00&quot;)
  const [ms, setMs] = useState(&quot;00&quot;)
  const [m, setM] = useState(&quot;&quot;)
  
  function handleStart(){
    if(isPlaying){
      setIsPlaying(false)
      setStopTime(time)
    }
    else{
      setIsPlaying(true)
      document.body.querySelector('#resetBtn').style.visibility = &quot;visible&quot;
      setStartTime(Date.now())
      playTime()
    }
  }
  
  function playTime(){
    setTimeout(()=&gt;{
      setElapsedTime(Date.now() - startTime)
      setTime(stopTime + elapsedTime)
      sec = Math.floor(time/1000%60)
      if(sec &lt; 10) setS(&quot;0&quot; + sec)
      else setS(sec)
      msec = Math.floor(time/10%100)
      if(msec &lt; 10) setMs(&quot;0&quot; + msec)
      else setMs(msec)
      // set min
      if(s == 0){
        min = Math.floor(time/60000)
        if(min &gt; 0) setM(min + &quot;:&quot;)
      }
    }, 1)
  }
  
  useEffect(()=&gt;{
    if(document.body.querySelector('#startBtn').checked) playTime()
  }, [time])
  
  function resetTime(){
    document.body.querySelector('#startBtn').checked = false
    document.body.querySelector('#resetBtn').style.visibility = &quot;hidden&quot;
    setTimeout(()=&gt;{
      setIsPlaying(false)
      setTime(null)
      setStopTime(0)
      setS(&quot;00&quot;)
      setMs(&quot;00&quot;)
      setM(&quot;&quot;)
    }, 1)
  }
  </code></pre>