How to use the setState Method In ReactJS

It re-render the component if some state or props of that component changed.

Syntax:

this.setState({ state: this.state });

Example: As we can see from the below code when we type in the text box the setState() method calls that set the latest value of name and re-render the component each time.

Javascript




// App.js
 
import React, { Component } from 'react';
 
class App extends Component {
  state = {
    name: '',
  }
 
  handleChange = (x) => {
    const { name, value } = x.target;
    this.setState({
      [name]: value,
    });
  }
 
  render() {
    return (
      <div >
        Name:
        <input type="text" name="name" onChange={this.handleChange} />
        <div>
          <h4> Hi, {this.state.name}!</h4>
        </div>
      </div>
    );
  }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

What’s the difference between forceUpdate vs setState ?

The difference between forceUpdate() and setState() is i.e setState() re-render the component if some state or props of that component is changed. When we call setState() the lifecycle method shouldComponentUpdate() method calls automatically which decides if the component should re-render or not. The shouldComponentUpdate() method exits the update life cycle if there is no reason for re-rendering.

Note: We should try to stop using forceUpdate() wherever possible and read from this.props and this.state during rendering.

Table of Content

  • Using the setState Method
  • Using the forceUpdate Method

Similar Reads

Steps to Create React Application:

Step 1: Create a react project folder and install locally by npm i create-react-app....

Using the setState Method:

It re-render the component if some state or props of that component changed....

Using the forceUpdate Method:

...

Difference between forceUpdate vs setState method are:

It re-render the component without even changing the state or props....