React State and setState in Class Components

In this tutorial, we will learn how to use the state object to store the data and setState() method to update the data in class components.

A state is a built-in object in React class components. In the state object, we store property values that belong to the component. When the state object changes, the component re-renders. We use the setState() method to change the state object in a class component.

Example 1: State and setState in Class Components

Create State Object in Employee Component

Let's create an Employee class component and create and initialize the state object in the constructor:

import React from "react"

class Employee extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            firstName: "Ramesh",
            lastName: "Fadatare",
            email: "[email protected]"
        }
    }

    render(){
        return (
            <div className="center">
                <h1> Employee Details</h1> <hr />
                <p>{this.state.firstName}</p>
                <p>{this.state.lastName}</p>
                <p>{this.state.email}</p>
            </div>
        )
    }
}

export default Employee

Let's import the above component into the App component and see the result in the browser:

import './App.css'
import Employee from './components/Employee'

function App() {
  return (
    <div>
      <Employee />
    </div>
  )
}

export default App

Using setState() Method to Update the State Object

To change a value in the state object, use this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s). 

For example, let's add a button with an onClick event that will change the lastName and email properties of the employee:
import React from "react"

class Employee extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            firstName: "Ramesh",
            lastName: "Fadatare",
            email: "[email protected]"
        }
    }

    updateEmployee(){
        this.setState({
            lastName: "jadhav",
            email: "[email protected]"
        })
    }

    render(){
        return (
            <div className="center">
                <h1> Employee Details</h1> <hr />
                <p>{this.state.firstName}</p>
                <p>{this.state.lastName}</p>
                <p>{this.state.email}</p>

                <button onClick={() => this.updateEmployee()}>Update Employee</button>
            </div>
        )
    }
}

export default Employee

Example 2: state and setState()

Creating the state Object

Let's create a StudentComponent and create and initialize the state object in the constructor:
import React, { Component } from 'react'

class StudentComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 firstName: "Ramesh"
        }
    }

    render() {
        return (
            <div>
                <h1> Hello Student</h1>
            </div>
        )
    }
}

export default StudentComponent
The state object can contain as many properties. For example, let's specify all the properties your component need:
import React, { Component } from 'react'

class StudentComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 firstName: "Ramesh",
                 lastName:"Fadatare",
                 rollNo: 123,
                 age: 20,
                 books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
        }
    }

    render() {
        return (
            <div>
                <h1> Hello Student</h1> <hr/>
            </div>
        )
    }
}

export default StudentComponent
Now, we have seen how to create state and initiate the state object in a component. 
Let's see how to use state object in the component.

Using the state Object

Refer to the state object anywhere in the component by using the following syntax:
this.state.propertyname
Example: Refer to the state object in the render() method:
import React, { Component } from 'react'

class StudentComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 firstName: "Ramesh",
                 lastName:"Fadatare",
                 rollNo: 123,
                 age: 20,
                 books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
        }
    }

    render() {
        return (
            <div>
                <h1> Student Details</h1> <hr/>
                <h3> First Name: {this.state.firstName }</h3>
                <h3> Last Name: {this.state.lastName }</h3>
                <h3> Roll No: {this.state.rollNo } </h3>
                <h3> Age: {this.state.age }</h3>
                <h3> {this.state.books} </h3>
            </div>
        )
    }
}

export default StudentComponent
Let's import above component into the App component and see the result in the browser:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import StudentComponent from './components/StudentComponent';

function App() {
  return (
    <div className="App">
         <header className="App-header">
            <StudentComponent />
        </header>
    </div>
  );
}

export default App;

Hit URL http://localhost:3000/ in Browser

Changing the state Object using setState() Method

To change a value in the state object, use this.setState() method.
When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).
For example, let's add a button with an onClick event that will change the rollNo and age of properties of the student:
import React, { Component } from 'react'

class StudentComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 firstName: "Ramesh",
                 lastName:"Fadatare",
                 rollNo: 123,
                 age: 20,
                 books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
        }
    }

    updateStudent(){
        this.setState({
            rollNo: 124,
            age: 21
        })
    }
    render() {
        return (
            <div>
                <h1> Student Details</h1> <hr/>
                <h3> First Name: {this.state.firstName }</h3>
                <h3> Last Name: {this.state.lastName }</h3>
                <h3> Roll No: {this.state.rollNo } </h3>
                <h3> Age: {this.state.age }</h3>
                <h3> {this.state.books} </h3>
                <button type="button" onClick={() => this.updateStudent()} >Update Student Details</button>
            </div>
        )
    }
}

export default StudentComponent
Click on the "Update Student Details" button will update student details in the browser:

Related Tutorials

Comments