forceUpdate()

In React, when the props and state of the component are changed the component automatically re-render but when the component is dependent on some data other than state and props. In that situation forceUpdate is called to tell that component requires re-rendering. Calling forceUpdate() will forcibly re-render the component and thus calls the render() method on the component skipping the shouldComponentUpdate() method.

Example: Now write down the following code in the App.js file.

App.js




import React from 'react';
class App extends React.Component{
  forceUpdateHandler=()=>{
    this.forceUpdate();
  };
   
  render(){
   console.log('Component is re-rendered');
    return(
      <div>
       <h3 style={{backgroundColor: "green"}>
        Example of forceUpdate()
        method to show re-rendering
       </h3>
        <button onClick= {this.forceUpdateHandler} >
         FORCE UPDATE
        </button>
        <h4>Random Number : 
           { Math.floor(Math.random() * (100 - 1 +1)) + 1 }
        </h4>
      </div>
    );
  }
}
 
export default App;


Output:

ForceUpdate

What’s the difference between forceUpdate vs render in ReactJS ?

In this article, we will learn about the difference between forceUpdate vs render in ReactJS. In ReactJS, both forceUpdate and render are related to updating the UI, but they serve different purposes.

Table of Content

  • render()
  • forceUpdate()
  • Difference between forceUpdate vs render

Similar Reads

Prerequisites:

NodeJS or NPM React JS render() forceUpdate...

render():

In React, the render() method is most important when you are working with a class Component. Without this method, a class component cannot return the value.  All the HTML code is written inside the render() method. render() is a part of the React component lifecycle method. It is called at different app stages. E.g. When the component is first made or ready....

forceUpdate():

...

Difference between forceUpdate vs render:

In React, when the props and state of the component are changed the component automatically re-render but when the component is dependent on some data other than state and props. In that situation forceUpdate is called to tell that component requires re-rendering. Calling forceUpdate() will forcibly re-render the component and thus calls the render() method on the component skipping the shouldComponentUpdate() method....