Simple Re-render
This approach uses a counter application. When the button is clicked it update the state data that cause the automatic re-render in the app and child components.
Example: Here props in a child are not modified but it is forced re-rendered when counter state changes.
// App.js
import { useState } from "react";
import Child from "./Child"; // Child Component
function App() {
const [Count, setCount] = useState(0);
console.log("Parent rendered");
return (
<div className="wrap">
<button onClick={() => setCount(Count + 1)}>
Increase
</button>
<p>Count:{Count}</p>
<Child name={"ABCD"} />
</div>
);
}
export default App;
// Child.js
function Child(props){
console.log("Child Rendered");
return(
<div>
<h1>Child Name={props.name}</h1>
</div>
);
}
export default Child;
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 both component rerenders on changing counter state.
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.