DEV Community

Cover image for Console current value of state in react js
Shaban-Eissa
Shaban-Eissa

Posted on

Console current value of state in react js

we have a button and counter, we need once we clicked on button to console the current value of counter not the previous value

Image description

This code will display the previous value of counter because the state is asynchronous so console.log(counter) will run first before state changed, and that is why we see the previous value of counter when write console.log(counter) in increment function

That is result of above code

Image description

we can solve this by using useEffect and write console.log() in useEffect like this code :

Image description

and now if we clicked on button mean that we changed the state of counter and then useEffect will run becuase it depend on counter state, so we can see the current value of counter in the console

Image description

Top comments (0)