Different ways to update state in useState hooks

useState hooks help to maintain a local state of a component. There are two different ways to update the state using the useState hook.

Let's have a state for counting the number of clicks of a button,

const [clicks, setClicks] = useState(0);

The initial count will be 0.

1. Replace the state

On every button click, you can simply add the count by 1,

const handleClick = () => {
  setClicks(clicks + 1);

This way of updating the state works very well if your updates are synchronous and done only in one place.

But if the click value gets changed asynchronously in different places, then easily your clicks value will be stale. We will see about the stale state in detail in a separate post. And that makes your count go wrong.

In order to avoid a stale state, you can always get the previous state value and replace it.

2. Mutate the previous state value

const handleClick = () => {
  setClicks(prevCount => prevCount + 1);

This way, you can always get the latest state value and then calculate the next state based on it.