DEV Community

Cover image for React setState Asynchronous Behaviour
Mr-Usman
Mr-Usman

Posted on

React setState Asynchronous Behaviour

Most of the time, developers write code and it doesn't work as expected because their mental model works WRT to code they see or write but they actually don't know how Javascript V8 compiles or runs their code under the hood so they ended up in frustration or starting to blame the language in some odd way, anyways let's get started with setState how it really works!

here, I am assuming u know the basic understanding of how we can update the component State in React, or the same thing goes for the React Native.

1.Use setState with the object Approach

what happens if we try to use setState multiple times in a single function call and all of setState updating the same value?

Here the concept of Reconciliation comes into play so at run time React knows the state was being tried to update with for the same key from the state object so you will be surprised by seeing the updated value resulted from the only last setState function call and above ones have no any effect on the final result.

Example: https://codesandbox.io/s/infallible-aryabhata-752b5?file=/src/App.js

2.Use setState with the functional Approach

Vice versa from the case study point 1. when we pass(use) the function in the setState for the state updating the javascript engine or specifically in React will show the result of every setState call rather than only last call as seen in the above scenario.

Example: https://codesandbox.io/s/frosty-sound-vrp6n?file=/src/App.js

Top comments (3)

Collapse
 
ignasave profile image
Ignacio Martin Vazquez

But why in the second approach ir increments by 3 and not by 4?

Collapse
 
mrusman profile image
Mr-Usman

There are three times a call to setState for the setState for increment operation so that is why the value is updating to 3.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.