DEV Community

Discussion on: How not to update states in React!!

Collapse
nehal_mahida profile image
Nehal Mahida Author

Thanks, man, You put great points 🙏🏻

Trust me it adds value to my post.

Regarding the title, Yes the first approach works most of the time.
But don't you think if programmers follow the second approach from starting itself, they don't need to worry about state updates ( asynchronous or synchronous) at the end?

As the world moves towards pair or group programming it is a good habit to make a RIGHT approach a default one. 🤗

Happy Coding!!

Collapse
lukeshiru profile image
LUKESHIRU

As I mentioned in my initial comment, the problem with the second approach is that you're scheduling more state changes (so you're making React do more work than what it should). The idea with having the value and the callback options is that you should use the one that does the job correctly, not use "always the same". The rule is simple: Do you need the current state? Use the value approach. Do you need the past state or are you running outside React's scheduler? Use the callback.

I would even dare to say that usually the callback approach is a "code smell", because we actually need to use it in extremely particular scenarios.

Thread Thread
nehal_mahida profile image
Nehal Mahida Author

You are right. My article is all about when you need the previous value of the state then and then you need to use the callback function in setState otherwise it's fine.