Forced Re-render
This approach shows how we can manage to force the rendering of a component without any state, prop or parent state update. This approach uses a usestate hook to force the component to re-render.
Example: A button is given which on click cause a force re-render of the document.
/* App.css */
.App {
text-align: center;
overflow-y: scroll;
}
.geeks {
color: green;
}
// App.js
import { useState } from "react";
import "./App.css";
function App() {
const [Count, setCount] = useState(0);
const [, forceRender] = useState(undefined);
const handleClick = () => {
forceRender((prev) => !prev);
};
console.log("App.js rendered");
return (
<div className="App">
<h1 className="geeks">w3wiki</h1>
<button onClick={() => setCount(Count + 1)}>
Increase
</button>
<p>Count:{Count}</p>
<button onClick={() => handleClick()}>
Force Update
</button>
</div>
);
}
export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output: Check the rendering dialogue in the console. it shows force re-renders on clicking the button
.
Re-rendering Components in ReactJS
Re-rendering components in ReactJS is a part of the React Component Lifecycle and is called by React only. React components automatically re-render whenever there is a change in their state or props and provide dynamic content in accordance with user interactions.
Re-render mainly occurs if there is
- Update in State
- Update in prop
- Re-rendering of the parent component
Unnecessary re-renders affect the app performance and cause loss of users’ battery which surely no user would want. Let’s see in detail why components get re-rendered and how to prevent unwanted re-rendering to optimize app components.
Table of Content
- Simple Re-render
- Optimized Re-render or Re-render prevention
- Forced Re-render
Prerequisites:
Steps to create the application
Step 1: Create a new React project named counter-app by running the below-given command.
npx create-react-app counter-app
Step 2: Once the installation is done, you can open the project folder as shown below.
cd counter-app
Step 3: After creating the React JS application, install the required module by running the below-given command.
npm install react-desktop
Application Structure:
Project structure will look like the following.