How State works in React
While React is just a small library that we all enjoy (right? ), it can be both confusing and difficult at times. I believe I can safely say that "state" is one of the ambiguities, and only a few people fully comprehend it.
When does React re-renders ?
First, we created a count variable to record how many times the component was updated using the handle. Let's look at the results in the browser now.
Even though the count value is getting updated on every click , IT DOES NOT trigger the component to rerender .
Let's try it the other way now , the "setState" way :
note that i'll be using useState hook for this example but it works the same for class based components
Conclusion => React rerenders everytime the state changes
useState is Asynchronous
Whaaaaatttt ??!! yeah i must be crazy to say that but pleaase give me a moment to explain myself , if we go back to the previous example and try to console log "count" , we'll see something quite interesting :
if you look at handleClick , setCount is before console.log() but for some reasons , it logs the Previous State or there's some kind of a delay in there .
It's so important to understand this to avoid future unwanted bugs .
let's just take this to the next level , in the code below what am trying to do is to increment by 2 in Increment function :
the reason why this behavior happened is because setState is asynchronous , remember my previous post about vdom and batch update ? when the state changes it doesn't rerender right away it makes another virtual dom copy to point out the where the change happened (diffing algorithm) and waits for some time (ms) for another possible changes in the dom and then it changes the actual dom . since we established that setState is async , both setCount (first and second) have the same old value of count since it was not changed immediately .
To properly update this what we should do is pass a callback function as a first parameter of setCount , that takes the previous state as an argument note that ("prev" is just a naming you can call it whatever you want , some people call it current state ) :
Thank you all for reading , i hope it was informative , this enough for this article as i don't want it to take longer in the next article we will be t alking about useState best practices .
Have a nice day <3 see you later