How to force ReactJS to re-render on every setState call ?
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:
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.
Step to Run Application: Run the application using the following command from the root directory of the project:
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.