How to use the forceUpdate() method In ReactJS
The forceUpdate method forcible re-render the component. When forceUpdate is called it directly calls the render method by skiping other lifecycle methods and update the interface.
Caution: Even though forceUpdate solves our problem but it is advised to use setState or changing props to re-render a component as forceUpdate method skips the proper lifecycle of rendering of a component. See this for detail.
Example: This example implements re-render forcibly using the forceUpdate method.
Javascript
// Filename - App.js import React, { Component } from "react" ; class App extends Component { reRender = () => { // force update this .forceUpdate(); }; render() { return ( <div> <h2>Random Number Generator</h2> <p> Your Number:{ " " } {Math.floor(Math.random() * 10) + 1} </p> <button onClick={ this .reRender}> Generate! </button> </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:
How re-render a component without using setState() method in ReactJS ?
In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState().