Use The Function Version Of React Hooks If Your New State Depends On The Previous State

TopicSource
๐Ÿงฉ ReactTop 6 React Hook Mistakes Beginners Make - YouTube

Using the function version avoids side effects that happen due to React updating the state asynchronous.

If a state variables' value is dependent on the previous value (e.g. setCount(count + amount)), always use the function version of the hook.

setCount(currentCount => {
	return currentCount + amount
})

React updates the state asynchronous. An addition, it updates the state variable after the next render, so that multiple useState-Hooks could be batched together before this re-render.
This can have weird side effects where the state is not updated properly if the previous useState is not done yet. Using the function version avoids this issue.


  1. Pros and cons of React