Common Mistake With React State Update

Hey Guys,

I have often seen one common mistakes being made by some beginner React devs which is to update React state.

How do you guys update your state if it depends on the previous value? If you are following below method to update react state then you are doing it wrong!! 😮

Above method will works fine, but sometimes when you have a state that updates very frequently which method will you prefer ?

In official documentation of react its mention :

this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

So What should be correct approach ?

Here we go…

To handle this situation, react allows us to pass a function in setState, which will give us the previous value of a state.

Here react guarantees us that the value is always updated correctly. 🤩

Please tell me in a comment have you ever faced any problem because of state updates? I would like to hear your feedback.

If you like this article like, share and bookmark this article!!

Thanks for reading

You can visit my youtube channel “JavaScript Centric”and subscribe it for interesting videos. https://www.youtube.com/channel/UC9MmyicGIveu0AId8OFAOmQ