Understanding the Basics of State in React

Aymes S.
3 min readOct 29, 2020
I know, I know…but you have to learn it!

What is state?

State is a JavaScript object that stores a component’s data and determines what the component maintains. It starts with a default value and is expected to change during the component’s life. That component must keep track of its changing information.

Remember props is a JavaScript object that is expected NOT to change. They are immutable. A component cannot change its props , but is responsible for putting together the props of its child components.

from Reactjs.org

State is different in where a component can change its own data when it needs to. When we introduce state to a component, it needs to be a class-based component. This means class App extends React.Component and NOT function App.

We will always start state with a constructor method. A constructor method is a specific method, built into JavaScript, that initializes parts of the class that it is in. This is where we will be initializing values. Once you add aconstructor, it will always call to a global function called super. It goes to the parent class and grabs the goodies and brings it down to that class can use those goodies. this.state will always equal to an object. State is also accessed through this.state.

Below, this is where we set the INITIAL state:

class Jar extends React.Component {
constructor() {
super()
this.state = {
count: 0
}
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button>Add $$ to Jar</button>
</div>
)
}
}

In this example, we are initializing a count to be 0. We are rendering to the screen the count along with a button that will increase the count. In order to increment our count, we are going to create an event listener called handleClick.

setStatecomes from the parent class. It takes in an object literal. Thanks to setState, we won’t ever modify the state directly. This is what will prevent us from hardcoding any sort of data in the future. setState ensures that the components affected by any changes in state are re-rendered to our browser.

This is how we will ALTER the state:

handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}

prevState is a name given to the argument passed to setState’s callback function. It holds the value of state BEFORE the setState was triggered by React. It is important to know what the previous state was when you want to update the new state value.

class Jar extends React.Component {
constructor() {
super()
this.state = {
count: 0
}
}
handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.handleClick}>
Add $$ to Jar</button>
</div>
)
}
}

There we have it!

tl:dr; There is no point of using state if the data is not being altered.

--

--