Skip to content
Related Articles

Related Articles

Improve Article

How to force ReactJS to re-render on every setState call ?

  • Last Updated : 31 Mar, 2021
Geek Week

When the state or props of a React component change, the component will immediately re-render. Many User Interface (UI) components are instantly re-rendered when the state is updated from somewhere in the code.

If we want to render the component without any changes, we can use the foceUpdate() method. When we call forceUpdate(), it will re-render the component and skip shouldComponentUpdate() method.

The shouldComponentUpdate() method allows your Component to exit the Update life cycle if there is no reason for re-render.

Syntax:

this.forceUpdate()

Creating React Application:



  • Step 1: Create a React application using the following command:

    npx create-react-app foldername

  • Step 2: After creating your project folder i.e., foldername, move to it using the following command:
    cd foldername

Project Structure: It will look like the following.

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import React from 'react';
class App extends React.Component {
  
  handleForceUpdate = () => {
    this.forceUpdate();
  };
  
  render() {
    return (
      <div>
        <h3>
         Example of forceUpdate() method to 
         show re-rendering <br></br>
         without changing state or props
        </strong>
        <button onClick={this.handleForceUpdate} >
          FORCE UPDATE
        </button>
        <h4>Number is : 
           {Math.floor(Math.random() * (100000 - 1 + 1)) + 1}
        </h4>
      </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:

Explanation: As we can see from the above example, the component is re-rendering without changing props or state because of the forceUpdate() method call. The random number is re-generating when the component is re-render.

My Personal Notes arrow_drop_up
Recommended Articles
Page :