Next.js Discord

Discord Forum

[bug] increment number correctly

Unanswered
Carolina Dog posted this in #help-forum
Open in Discord
Carolina DogOP
I have counter
function Home() {
    const [counter, setCounter] = useState<Number>(0);

    const handleClick = () => {
        setCounter(counter+1 );
        console.log(counter)
    }
return (
    <main>
          <p>Hello World</p>
          <div>Counter: {counter} </div>
          <button onClick= {handleClick} >Click Me</button>
          
     </main>
  );
 }

counter on Div is always (1 More ) than the counter I see on the console

why is that ?? how to fix it ??

Im trying to run an event using useEffect when counter is 10 but runs when its 11 on div :/

18 Replies

the value is only updated on next render
and that isnt right after you changed/updated
Sun bear
For console.log states i would recommend to use effect and log it onchange.

useEffect(() => {
console.log(counter)
},[counter])
yeah as that would run on next render, but you dont even need useEffect there... just running it outside should redo it as counter chances
Flemish Giant
Try to update the previous state or with previous value use setCounter(prev => prevr+1 ) or setCounter(counter => counter+1 );
those 2 examples are the same shouldnt fix any issue here
Flemish Giant
const [counter, setCounter] = useState<number>(0);
the number should be in small
good suggestions, however can we get to the topic of the actual issue instead of unrelated things
Flemish Giant
Its because the setCounter update the state but its take a littel time but you console the counter which contain the previous state that why its alway opne step behind
even i search it to confirm the update state is aasynchronous task so it make take some time thats why the issue is
if there is also any other reason pls tell it to me more thats i know
Flemish Giant
Nice you already know this are you testing people out thats great
and thanks for sharing
Flemish Giant
You you are a helper nice man you doing a good job i know the answer but you increase the knowledge a bit
well its not the "little time" you mentioned, even the docs shows a 5sec delay and its still the same
but yeah thanks i try to be as acurrate as possible (i prob wasnt initially, but this docs is good example and source)