DEV Community

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

Posted on

State in React: What's the big deal?

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 all about and why there was so much ado about it. I read some guides and watched some videos, but only ended up with a vague idea of what it was all about. As a result, It took me a very long time before I could get up and running with the library.

This guide is to help demystify the subject and make it very easy for a novice to understand what the subject is all about.

SO WHAT EXACTLY IS STATE?

State is simply the data that an application contains at a given instance.

Consider for example, a simple React component that renders a simple div. The div contains 2 buttons and a heading tag. When the component loads, the heading tag displays the number "0".

Alt Text
The state of the application right now is ZERO. This is called the Initial State. When I click on the "Increase" button, the zero changes to 1. This becomes the new state of the component. When I click again, the "1" changes to "2". So the green button thus changes the state of the component by simply adding 1 to the existing number displayed.
Alt Text
The same goes for the red "Reduce" button. It changes the state of the component by reducing the value that is being displayed by 1. In the screenshot below, the state of the component is now "-1".
Alt Text

HOW TO CREATE STATE

There are 2 ways to define State in React:

1.) In class based components, State is defined as an object. It is as simple as writing "State = {}" outside the render method. Within the state object, you define the Initial State of your component like so:

Alt Text

Inside the State object, you set the initial state of the component to be zero(0). To show the state in your browser, you have to pass the content of the state object into the div that your render method will return. So when the app loads, you should see 0 displayed on the browser.

  1. The second method of defining state is by using React Hooks. Hooks are meant to be used in functional based components like so:

Alt Text

The useState hook is an array that comprises of 2 values:

1.) The variable you want in your state(named ‘count’ in our example above) and
2.) The method you will use to update the variable(This is usually written as "setVariablename". E.g: If the name you give to your variable is "product", the method becomes "setProduct").

Using array destructuring, you extract the 2 values from useState and set the initial value of your state within the bracket(In this case, it is zero).

HOW TO UPDATE THE STATE

As you might have noticed from previous examples, the state of the component keeps changing at various points. First it was 0, then 1, 2, 3, 4 etc at a click of the increase button. Same with the reduce button, the state changes when the button is clicked. How can you change the state of your application?

React does not allow you to change the state directly. Meaning that once you've defined the state, you cannot try to change it's value anywhere else by calling it directly.

There is a method provided by React to help you update the state. This is the setState method. Here is how you can update your state if you are using a class-based component:

Alt Text

Simply pass in the state object into the setState function and then replace the Initial state value with the new value you want it to change to. For example, if you want it to change from 0 to 9, you can just say:

" this.setState( {count: 9} ) "

In the example above, I added the onClick method to the second button labelled "Increase" and passed in a function which then returns the setState method. The setState method contains an object with "count" as the key because the key in the state is "count". To change the value of the count, I had to access the original content of the state object using dot notation like so " this.state.count " , and then adding 1 to it. So each time we click on the increase button, it would call on setState which would in turn add 1 to whatever number the state contains at that instance.

In Functional components, updating state is even easier. We simply use the setVariable method which we already have in the array that we destructured from React.useState, like so:

Alt Text

Within the setVariable method(in our case, it's setCount), we pass in a callback which takes the current value of our state(prevCount) as a parameter and adds "1" to it. It then becomes the new value we want our state to update to.

CONCLUSION

So that is how we update the state of a React Component. I hope this article has helped you to understand State a little bit better. Thank you for reading!

PS: If you liked the article, or learnt anything from it, please like, share and comment. You can also follow me on twitter or github. I always follow back. Cheers!

Top comments (14)

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🙏