React Tutorial For Beginners - Working on State in React

Introduction

React is an Open Source JavaScript library. It is used for developing scalable, simple, and fast front-ends for web & mobile applications. It handles the view layer of mobile and web applications. React is flexible and can be used in any application.

Description

In this article, we learn about the State in React, what its importance is, and the fundamental understanding of steps to start managing the state in a React-based application. Application user interfaces are dynamic and change over time. And if any changes we do on the Component Class members for various user actions should get updated into Browser UI. Let's understand it using State in React. 

Please visit the React articles to understand the beginning.

The below React articles are for a basic understanding of React sample applications.

What is State in React?

  • The state allows React components to change their output over time in response to user actions.
  • State is similar to props, but it is private and fully controlled by the component.
  • The state contains data specific to a given component that may change over time.
  • The state is user user-defined plain javascript object.
  • React provides a method called setState()  for managing component states.
  • setState() tells React that this component and its children should be re-rendered with the most updated state.

State in React with example


index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  ClickButtonMethod = () => {
      alert('Clicked Button Method Show Alert');
  }
  render() {
    return <div>
        <h2>React State in Employee Component...</h2>
        <button onClick={this.ClickButtonMethod}>Click Button Method</button>
    </div>
  }
}

const element1=<Employee></Employee>
ReactDOM.render(element1,document.getElementById("root"));

Code Description

Create a Component Class called Employee and we implement render method. Let's return div which contains one h2 tag, display text called Employee Component, and place a button in the Text with Text as Click Button Method. Let's Create a function called ClickButtonMethod, in which let's show a simple alert message, and to call this function on Click of the button, we use the onClick attribute. and let's Pass the ClickButtonMethod to it. Let's Call this Component and render it to our DOM. Lets save these changes, navigate to our browser and we can see the Employee Component contents are being shown.

Output

React state

Click on the Button and we can see the alert is being shown with the message.

Let's make another example


index.js code

Here, I want to keep a track on how many times the button is being Clicked.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  counter=0;
  ClickButtonMethod = () => {
        this.counter=this.counter+1;
        alert('Clicked on addEmployee Method');
        alert('Add Employee Button is clicked '+ this.counter +' times' );
    }
  render() {
    return <div>
        <h2>React State in Employee Component...</h2>
        <button onClick={this.ClickButtonMethod}>Click Button Method</button>
    </div>
  }
}

const element1=<Employee></Employee>
ReactDOM.render(element1,document.getElementById("root"));

Code Description

Lets create a counter variable and initialize with zero. In ClickButtonMethod function, let's increment this counter and display that in the alert. Let's save these and navigate to the browser, Click on the button several times and one can see that counter is incremented each time when the button is Clicked.

Output

Now, We come to the point why we need State in React for State management. Let's understand with an example.

Lets remove the alerts we are showing and create one paragraph element and display the counter value in it.

index.js code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  counter=0;
  ClickButtonMethod = () => {
        this.counter=this.counter+1;
        alert('Clicked on addEmployee Method');
        //alert('Add Employee Button is clicked '+ this.counter +' times' );
    }
  render() {
    return <div>
        <h2>React State in Employee Component...</h2>
        <p>
            <button onClick={this.ClickButtonMethod}>Click Button Method</button>
          </p>
          <p>
          Click Button Method clicked : <b>{this.counter}</b>
          </p>
    </div>
  }
}

const element1=<Employee></Employee>
ReactDOM.render(element1,document.getElementById("root"));

Output

Button click

Let's save these and navigate to the browser, Click on the button several times and one can see that the counter is not incremented each time when the button is Clicked. That’s because the change we are doing on the counter property in the component class is not getting rendered into our UI.

How to fix this?

React introduces, a new concept named “state” which allows React components to change their output over time in response to user actions without violating this rule. State is similar to props, but it is private and fully controlled by the component. The state contains data specific to a given component that may change over time. The state is user defined plain javascript object. By adding a “local state” to a class, we can move data from the props onto a state which can be updated. Let's create a state object, and add a counter property in that object with a default value of 0. When the ClickButtonMethod method is Called, we have to incremenet the counter and this change should be updated in the UI. React provides a method called setState()  for managing component states. 

index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  state={counter:0};
  ClickButtonMethod = () => {
    this.setState({counter:this.state.counter+1});
    }
  render() {
    return <div>
        <h2>React State in Employee Component...</h2>
        <p>
            <button onClick={this.ClickButtonMethod}>Add Employee</button>
          </p>
          <p>
            Add employee button clicked : <b>{this.state.counter}</b>
          </p>
    </div>
  }
}

const element1=<Employee></Employee>
ReactDOM.render(element1,document.getElementById("root"));
  • We have created a state object and added a property as a counter with an initial value of zero.
  • When the ClickButtonMethod method is called we increment the counter value fetching from the state, creating an object, and passing to a method called setstate();
  • Setstate() tells the react that its component and children should be rerendered Most updated state.

Output

Employee component

Here setState() tells React that this component and its children i.e. sometimes delayed and grouped into a single batch should be re-rendered with the most updated state. Lets Pass an Object which contains counter and write an arrow function which increments the Counter.  Lets display the counter value from the state object we have created. Save these changes, go back to the browser and one can see that counter value is increment on multiple button clicks.

To make our understanding better on State in React, lets look at another example

Here, We want to have a textbox where user can enter a message and a label which should display the number of characters entered in the textbox. To implement this, we create a Component Class, Lets Create Constructor with props as the argument, lets make base class constructor call using super. Lets initialize state object with message property in it. Lets set default message as empty and default counter as 12.

index.js code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class CountTextBoxCharacters extends React.Component{

  constructor(props){

      super(props);

      this.state={

          message:'',

          counter:12

      };

  }

  onTextMessageChange(text){
      this.setState({
          message:'Message Box has '+text.length+' number of Characters'
      });
  }
  render(){
      return <div>
          <h2>Count Characters Component in React</h2>
          <p>
              <label>Enter Your Message : <input type="text" 
                          onChange={e=>this.onTextMessageChange(e.target.value)}></input></label>
          </p>

          <p>
              <label>{this.state.message}</label>
          </p>
          <p>
              <label>{this.state.counter}</label>
          </p>
      </div>
  }
}

class Employee extends React.Component {
  state={counter:0};
  ClickButtonMethod = () => {
    this.setState({counter:this.state.counter+1});
    }
  render() {
    return <div>
        <h2>React State in Employee Component...</h2>
        <p>
            <button onClick={this.ClickButtonMethod}>Add Employee</button>
          </p>
          <p>
            Add employee button clicked : <b>{this.state.counter}</b>
          </p>
    </div>
  }
}

const element1=<Employee></Employee>
ReactDOM.render(element1,document.getElementById("root"));

const element=<CountTextBoxCharacters></CountTextBoxCharacters>
ReactDOM.render(element,document.getElementById("root"));

 Implemented render method, Here we placed a textbox and a label. When a user enters the message in the textbox, this count message needs to be displayed on the label. Lets create function named onTextMessageChange which will accept the entered text in the textbox as a parameter. Change the state object message to display that the Message has this many number of characters. Let's call the function when the input changes by using onChange Event. Let's pass the text in the input element as a parameter to the onTextMessageChange function.

Call this in the Component and render this.

const element=<CountTextBoxCharacters></CountTextBoxCharacters>
ReactDOM.render(element,document.getElementById("root"));

Output

Count characters components

Save the changes, go back to the browser and as we keep entering the text, we can see that is being displayed in the label. Let's add one more variable to the state object named count and assign it to lets say a default value of 12. Now when the text is changed, we are triggering onTextMessageChange function and inside that, we call the setState method by passing the State Object which contains only the message. We are not passing the counter value. Let's display the Counter Value as well in another label. Save the changes, go back to the browser and as we keep entering the text, we can see that the Message is being displayed in one label. Counter value is also displayed in another label. State object is holding both Message and counter though we are not passing it again.

Write React Code using Online Editor

You can play with the React application Mobile platform using the below steps. Let's open the below URL and start coding.

Then open the below URL to add CDN links so that React can understand the syntax. Select JavaScript Preprocessor: babel.

The steps are already discussed in Part 4: Working on Function Components in React

Summary

In this write-up, we have learned the details below.

  • Know about State in React
  • Steps to start managing the state in a React
  • Understand State in React with an example
  • Count the number of characters entered in the textbox using React State

Thank You & Stay Tuned For More!

Up Next
    Ebook Download
    View all
    Learn
    View all