we have a button and counter, we need once we clicked on button to console the current value of counter not the previous value
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
we can solve this by using useEffect and write console.log() in useEffect like this code :
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
Top comments (0)