Does setstate method in react update the state immediately?

Does setstate method in react update the state immediately?

Sometimes understanding setState might be tricky. When you update two states one after another using setState and if the second state variable is dependent on the previous updated state, it may not show correct values often. This is because the setState does not fire instantly. Let us see how...

what are state and setState?

If you are new to React, State is something like a variable that is local to the particular component and may change over the lifetime of the component. Whenever we need to update the state, we should use the setState() method. The setState method updates the state and tells React that this particular component along with its children is to be re-rendered. React updates the virtual DOM and only re-renders the components that have been updated from the previous state. But setState does not fire instantly.

But why ..?

To optimize the performance of react application, react does not update the setstate immediately rather it updates multiple components in a single pass. This makes reading a state after calling setState a pitfall. Let's consider the below example

 const handleChangeText = e => {
    setValue(e); //e is updated as new value
    setCount(280 - value.length);
  };

Here, the setValue method does not update the value state immediately, so calling setCount to set count state may cause a bug.

I have read many blogs regarding this issue, and there were many solutions like wrapping everything setState insider async/await. But many have mentioned that we shouldn't change the actual working of react.

I have figured out how to handle the above situation, We know that a component re-renders when its state changes (reconciliation). So when we update the value using setState the component re-renders. Instead of creating a new state variable separately to count its length.

 const charLenght = value.length;
 const handleChangeText = e => {
    setValue(e); //e is updated as new value
  };

This is one way of handling this issue(not exactly, kind of ). If you come across any other ways to handle this. Let me know in the comments. Thanks for reading till the end.