DEV Community

Discussion on: State in React: What's the big deal?

Collapse
 
jz222 profile image
Timo Zimmermann • Edited

It can be dangerous updating the state like:

setCount(count + 1)

In these cases, it's better to make use of the callback function setCount provides:

setCount(prevCount => prevCount + 1)
Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Hello, thanks a lot for the feedback! I'll edit the post accordingly. May i know why it could be dangerous to update the state that way?

Collapse
 
jz222 profile image
Timo Zimmermann • Edited

In your example, you shouldn't run into any issues. However, as your app grows you may encounter that the state isn't updated reliably if you, for example, use the setter function inside a callback. This is a good example that demonstrates such a scenario. Click Delayed Counter (basic) and then immediately double click Immediate Counter. You will notice that that count will end up being 1, even though you clicked three times in total.

There was recently a Dev post on this topic and here you can find the related documentation.

Thread Thread
 
devmaturi profile image
Uche Ifunanya Okeke

Wow! Thank you so much for the references. I'll check them out. I have updated the article as well.