React State

Facebooktwitterredditpinterestlinkedinmailby feather

React State

The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change in the state over time happens as a response to user action or system events. The component with the state is called as Stateful components. It is a crucial part of the React component that determines the component’s behavior and how it will render. They are also responsible for making a component interactive and dynamic.

A state is to keep as simple as possible. The state can be set by using the setState() method, and on calling setState(), method triggers the UI updates. A state represents the local state or information. It can be modified or accessed directly by the component or inside the component. For setting an initial state before the occurring of any interaction, we have to use the getInitialState() method.

For example, suppose that we have five components that require data or information from the state, then we have to create a container component that will keep the state for all of them.

Defining the State

For defining a state, we have to first declare a default state of values for defining the component’s initial state. To do this, add a class constructor that assigns an initial state using this.state. The ‘this.state’ property can be rendered inside render() method.

Example:

The example given below will show you how to create a Stateful component using ES6 syntax:

Output:

React state

For setting the state, it requires to call the super() method in the constructor. This is because this.state is uninitialized before the calling of the super() method.

Changing the State

The state of the component can be changed by using the setState() method and passing a new state object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword to the toggleDisplayBio() method; otherwise, it cannot be accessible inside the toggleDisplayBio() method.

Example:

In the below example, we are adding a button to the render() method. On clicking the button triggers the toggleDisplayBio() method that display the desired output.

Output:

On clicking the button triggers the toggleDisplayBio() method

On clicking the Read More button, you will see the below output, and on clicking the show less button, you will get the output of above image.

Read More button, you will see the below output
Facebooktwitterredditpinterestlinkedinmailby feather