Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 31 Mar, 2021

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.



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.


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

Start Your Coding Journey Now!