Reputation: 775
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
Upvotes: 3
Views: 96
Reputation: 2609
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.
Upvotes: 0
Reputation: 851
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.
Upvotes: 2