In React, we use setState() to update the state of any component. So, we will learn why Is setState() asynchronous In React.
In React, we use
setState() to update the state of any component. Now
setState() does not immediately mutate this state, rather it creates a pending state transition. Accessing the state immediately after calling
setState() returns the existing value and not the updated one. As beginners in React, I’m sure most of us would have often faced this problem.
There is no guarantee of synchronous operation on
setState() and calls may be batched for performance gains. It is easy to forget that the
setState() is asynchronous, making it tricky for us to debug issues in your code. The
setState() also does not return a Promise. Using
await or anything similar will not work. There is also another case, where we tend to use multiple
setState() functions within the same block, and there are times where the state isn’t properly updated.