React hook: difference between setting the state with an argument or an arrow function

Viewed 54

I would like to expand on the state update in the following issue

React Hooks, rerender & keeping same state - how it works underhood?

Is there a difference between the two ways of updating {count} ? Are they strictly equivalent ?

<button onClick={()=>setCount**(count+1)**} >{count}</button>

<button onClick={()=>setCount(**savedCount => savedCount+1)**}{count}</button>

Thanks in advance

2 Answers

No they are not. You should prefer the latest, since it guarantees that the count your are working with is the latest version. When working directly with count rather than savedCount, it could have some updates still not applied.

No, there's no difference between the two.

The first one has the value of count through the concept of scoping.

The second one is getting the value from the useState hook using the callback, which always provides the latest value.

Related