The components in React will re-render only if the state of the component or the props passed to it changes but if we need to re-render the component if some data changes then we will use forceUpdate() method of React. Calling the forceUpdate() will forcibly re-render the component and thus calls the render() method of the component skipping the shouldComponentUpdate() method.
Tip: Normally, avoid all uses of forceUpdate() and only read from this.props and this.state in render().
Syntax:
component.forceUpdate(callback)
While there are certainly some use cases for using the forceUpdate() method but it’s better to use hooks, props, state, and context to re-render the component whenever you need.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Example: In this example, we are going to build a React application that re-render the component when the button is clicked by calling the forceUpdate() method.
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.
Javascript
import React from 'react' ; class App extends React.Component { reRender = () => { // Calling the forceUpdate() method this .forceUpdate(); }; render() { console.log( 'Component is re-rendered' ); return ( <div> <h2>GeeksForGeeks</h2> <button onClick={ this .reRender}> Click To Re-Render </button> </div> ); } } export default App; |
Note: You can apply your own styling to the application.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: