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:
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