Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Create and handle component's state

Exactly like props, every component has another place to store variables and their corresponding values. Values that can be used and are accessible inside the component. This object that stores all the variables is called state.

State works exactly like props but with a key difference. State and every property that lies inside, can change (so it’s what we call mutable).

Additionally when the state changes then automatically the render function of the component is called once again.

In our example we will use state to update live the paragraph’s content based on what the user types on the input field. We will update the value anytime we have a change of value to the input field form. Exactly like the previous example, but we will not use the ref object.

Anytime you want a live update to happen in react and you don’t want to handle all the things manually, you have to create a state object. The state is always created inside the constructor function at the beginning of the class. They way to instantiate a state object is through the:

this.state = {property: value} . This is the pattern that react accepts.

Of course you can have more than one properties that you want react to take a look at and re-render any time something there changes, but for now we will need only one.

So there we create a state property which in the future is going to hold the value of the input. At the beginning we set this equal to empty string. Then we add the value attribute to the input field, so we connect the value of the input field with that place in memory (the state.inputFieldValue).

Now that this connection was made, inside the handleChange function that is executed anytime we change something on the input field, we update the this.state.inputFieldValue.

We can change any value that lies within the state object through the this.setState function that accepts an object with the properties that you want to change and the corresponding values!

Attention: Anytime this function (this.setState) is executed,  automatically the render function of the component executes itself. This is why you SHOULD NEVER put any function that has a setState invocation, inside the render function. This will create an infinite loop and will make your browser to crash!!

Then the last thing we will do is inside the paragraph instead using any ref, we will put as a content the current state of the inputFieldValue. Any time the state of this property changes, the render function will render the paragraph with the new updated value. Simple as that!!