Updating state in Class Component

Updating the state to re-render in React class components using the setState method.

Syntax for Updating state in class component

this.setState((prevState) => ({
counter: prevState.counter + 1,
}));

Udating state to re-render in Class Component Example:

Re-render the component using set state in the react class component.

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
 
        this.state = {
            counter: 0,
        };
    }
 
    handleIncrease = () => {
        this.setState((prevState) => ({
            counter: prevState.counter + 1,
        }));
    };
 
    handleDecrease = () => {
        this.setState((prevState) => ({
            counter: prevState.counter - 1,
        }));
    };
 
    render() {
        console.log("Rendering!!!");
 
        return (
            <div
                style={{
                    textAlign: "center",
                    margin: "auto",
                }}
            >
                <h1 style={{ color: "green" }}>
                    w3wiki
                </h1>
                <h3>
                    React example for updating state to
                    re-render in class component
                </h3>
                <button onClick={this.handleDecrease}>
                    decrease
                </button>
                <span style={{ margin: "10px" }}>
                    {this.state.counter}
                </span>
                <button onClick={this.handleIncrease}>
                    increase
                </button>
            </div>
        );
    }
}
 
export default App;


Output: Open the browser and go to http://localhost:3000, you will see the following output.



How to update state to re-render the component in ReactJS ?

In React, when the state is updated it initiates to re-render the component and its child components to update the new data on the UI of the application.

Similar Reads

Prerequisites

React Functional Components React Class Components React Hooks...

Update state to re-render the component in React:

There are different ways in the functional and class components to update a state to re-render the component in React JS....

1. Updating state in Functional Component

Using React useState hook to access and modify the state in the functional component...

2. Updating state in Class Component

...