If you have been learning React you would probably came across the state word being used all over the place. The heart of every component lies in its “state”! But … what is this state we keep hearing about?

What is the state in React?

The “state” is the sum of the things inside of a React Component that can change AFTER that component is built.

The state of a React component is often used with a comparison to the props of that Component. Opposite to the state, the props cannot be modified once the component is created.

Let’s take the below codesandbox. Click around on some of the buttons:

It’s a Survey app made by multiple Question components. During the execution of our survey, there are two things that may change in a Question:

if the buttons are disabled and

the text of the answer status

Both changes will take place based on one check - if the user answered the question or not.

So, a question starts with state of a null answer:

class Question extends React.Component { state = { answer: null }; }

And, when any of the buttons are pressed, we will set on to the state of the component the received answer.

setAnswer = (pressedButtonText) => { this.setState({ answer: pressedButtonText }); }; //… <button onClick={this.setAnswer.bind(this, "YES")}> YES </button> <button onClick={this.setAnswer.bind(this, "NO")}> NO </button>

Please pay attention to the fact that, besides the initial declaration, you should always use this.setState(...) in order to change the value of the state.

And finally, the change in our state will determine the component visuals to be updated:

render() { // this will update the answer text {this.state.answer ? <i>You replied with {this.state.answer} to this question.</i>: <i>Please reply</i>} // this will update the enabled/disabled status of the buttons <button disabled={this.state.answer} onClick={this.setAnswer.bind(this, "YES")} >YES</button> <button disabled={this.state.answer} onClick={this.setAnswer.bind(this, "NO")} >NO</button> }

On the other side, the properties will keep their value constant throughout the execution of the Survey.

You can see also in the screencast about building a React Edit Cancel Text Input component how to use the react state in order to control the way a React component behaves.

Where to Initialize State in React

There are three places where you can initialize the state of a React Component.

1. Initialize the State as a class property

This is the approach we used for our Survey example. Just set the state directly inside the Component as a class property:

class MyComponent extends React.Component { state = { isLoading: false, totalScore: 10 }; }

Setting the initial state as a class property requires the least amount of codeing?. Usually, this is the preferred way of initializing the state.

2. Initialize the State via a Constructor

Initializing state inside the constructor looks like this:

class MyComponent extends React.Component { constructor(props) { super(props); this.state = { isLoading: false, totalScore: 10 }; } }

The constructor is the first method to be called when the component class is created. So, it’s the right place to initialize everything, including the state.

It is very important, when you use a constructor, to make sure that you call the parent class’ constructor: the super(props) line.

You can check this article if you want a more in-depth comparison. whether you should use a constructor or not. But the short answer is that you don’t need a constructor.

3. Initialize the React State using the getInitialState method

This way of initializing the state will only work with the when using the React.createClass from the older ES5 syntax.

var MyComponent = React.createClass({ getInitialState() { return { isLoading: false, totalScore: 10 }; } });

Unless you are bound to using ES5, try to avoid it.

Stateless components

As a complementary concept to the React state is the stateless components. They are also called “Presentation only” components or “Dumb components” (maybe this is not the most polite way of referring to them).

When the sole purpose of a React Component is just to show some information, and, if that component does not change, then it means that it is a React stateless component. It does not have a state.

For example, if the scope of a Question Component is just to show the question text, then it could be written like this:

class Question extends React.Component { render() { return ( <div className="question" style={{ borderColor: this.props.color }}> <b>{this.props.question}</b> </div> ); } } // and to make a Question <Question color="red" question="Was Mike Tyson one of the greatest boxers?" />

Furthermore, starting from React .14 we have a simpler way to write Stateless components. We can use the ES6 arrow functions and just say:

const Question = (props)=> { return ( {props.question} ) )

Or, if we want to take advantage of the JavaScript Named Params Destructuring and the fact that the arrow functions are returning the last used statement, then we can write:

```javascript

const Question = {color, question} =>(<div className="question" style={{ borderColor: color }}>

<b>{question}</b>

</div>)

If we take a look, we managed to reduce the code of our function from 7 lines to 3. Maybe not always fewer lines of code is the same thing as a more readable code, but still, a 50% decrease in the code lines is an improvement. Wrapping it up, I hope this small article made React state a bit more clear. As the main takeaways: - use the state object to control the things that will change AFTER that component is built - always use setState to modify the state of React Components - if a component is present only present information, and has no logic, then to make it a stateless component

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.