0

As a beginner to React, I am trying to build a stopwatch.
While the variables (numbers) displayed at screen are correct, trying to access said variables with a 'console.log()' or if-statement, it only reads the old value of that variable and not the actual one, displayed at the screen.
It very likely has a very simple solution, but I really could not find a solution per web or AI.

This is my used code, shortened, but still working:

import React, { useState } from 'react';

export default function Anzeige() {
    const [time, setTime] = useState({
        dezisec: 0
    });

    const Erhohen = () => {
        console.log(time)

        setTime((prevTime) => ({
        ...prevTime,
        dezisec: prevTime.dezisec+1
        }))

        console.log(time)
        logging()
    }

    const logging = () => {
        console.log(time)
    }

    const startTimer = () => {
        const t = setInterval(Erhohen, 1000)
    }

    return (
        <p onClick={startTimer}>{time.dezisec}</p>
    )
}

Explanation: When clicking on the p element, "dezisec" increases by 1 on the display/screen. But unexpectedly, both "console.log(time)" print out "dezisec: 0" the whole time. The same goes for the "logging()" function.

I already looked through possible solutions, but they seemed all to just change the location of the "console.log()" or used a function outside the "setTime", like the "logging()" function I used.

greybeard
  • 2,249
  • 8
  • 30
  • 66
Minz
  • 1
  • 1
  • React tries its best to reduce costly operations. Re-Rendering is a super-costly operation. So it has to do as less rerenders as possible. Even if you call `setTime(p => p + 1)` more than once, it'll still log the previous value. If you want to access the value in the moment it changes, you can log it like this: `setTime(prev => { const newVal = prev + 1; console.log(newVal); console.log(newVal); })` – webgodo Jun 25 '23 at 18:55
  • 1
    This question has been asked a million time already, and it is also covered [in the docs](https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value). – Arkellys Jun 25 '23 at 19:04

0 Answers0