Using useState hook with the previous state

· 117 words · 1 minute read

Let’s take a very basic use case of the useState() hook; updating the count variable on each click.

usestate

The code look perfectly fine and will work as expected in almost every time.

BUT the issue with this code is that setCount() doesn’t guarantee that the previous count that it’s going to use to either increment and decrement to get the next state will be the latest one.

To make sure that we always use the latest previous state for calculating the new state, we need to pass a callback function in the setCount rather than directly doing computation inside it.

usestate

This way we can guarantee that we are always using the latest state value before using it.