DEV Community

Cover image for State in React: What's the big deal?

State in React: What's the big deal?

Uche Ifunanya Okeke on June 24, 2020

While trying to understand how React works, the concept of State was something that constantly gave me a headache. I didn't understand what it was ...
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.

Collapse
 
sami_dghim profile image
Sami Dghim

Thank You

Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Thank you for reading, Sami!

Collapse
 
tuxedo_g profile image
Benvee

Nice one my dearie

Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Thank you Ben

Collapse
 
dmahely profile image
Doaa Mahely

State in React has been a sore point for me too. Thank you for the post 👌🏽

Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Thank you so much for the feedback, Doaa.

Collapse
 
ezzaffa88 profile image
SOFIEN

Thank You

Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Thanks for reading!

Collapse
 
legion_coreleon profile image
Core Leon

Nice job breaking this down .

Collapse
 
devmaturi profile image
Uche Ifunanya Okeke

Thank you so much, Coreleon🙏