Re-rendering Components in ReactJS - GeeksforGeeks

23 Sep, 2021
As we know React JS is an open source JavaScript library that is used for building user interfaces specifically for single-page applications. It is also known for providing fast user experience by only updating the parts of the UI that have changed. Rendering components is not in user hands, it is a part of React Component Lifecycle and is called by React at various app stages, generally when the React Component is first instantiated. A second or subsequent render to update the state is called as re-rendering. React components automatically re-render whenever there is a change in their state or props.
Prerequisites: Introduction to React JS, React JS | Lifecyle of Components
A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically. However, there may be cases where the render() method depends on some other data. Re-render can be caused due to any of the three reasons listed:
Update in StateUpdate in propRe-rendering of the parent component
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.
 
Why do components get re-rendered?
Let’s have a deeper look at the three causes of re-rendering mentioned before.
Update in state: The state change can be from a prop or setState change to update a variable(say). The component gets the updated state and React re-renders the component to reflect the change on the app.Update in prop: Likewise the change in prop leads to state change and state change leads to re-rendering of the component by React.Re-rendering of parent component: Whenever the components render function is called, all its subsequent child components will re-render, regardless of whether their props have changed or not.
Update in state: The state change can be from a prop or setState change to update a variable(say). The component gets the updated state and React re-renders the component to reflect the change on the app.
Update in prop: Likewise the change in prop leads to state change and state change leads to re-rendering of the component by React.
Re-rendering of parent component: Whenever the components render function is called, all its subsequent child components will re-render, regardless of whether their props have changed or not.
React schedules a render every time state changes (scheduling a render doesn’t mean this happens immediately, this might take time and be done at the best moment). Changing a state means React triggers an update when we call the useState function (useState is a Hook that allows you to have state variables in functional components). 
Example: Creating a simple Counter React Project will help to understand the concept of re-rendering components.
Prerequisite: Download VS Code and Node packages.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
Step 4: Open VS Code go to the explorer in VS Code (press crtl+shift+E). Next, go to src folder->New file as shown. And name it Child.js (this is the child component).
Making of child component
Project Structure: It will look like the following.
Project Structure
Step 5: Edit the code in the App.js file as shown. 
App.js File will have the following:
A state declared which would change and cause re-rendering,A message in the console which tells the parent component is rendered.Will return a div which consists of a button (which will increment the count and eventually result in state change) and a child component which has a prop that doesn’t change but is re-rendered unwantedly.
A state declared which would change and cause re-rendering,
A message in the console which tells the parent component is rendered.
Will return a div which consists of a button (which will increment the count and eventually result in state change) and a child component which has a prop that doesn’t change but is re-rendered unwantedly.
The code gives a message each time the component’s render function is called. Each time the count button is clicked state change is triggered. 
App.js 
Javascript
import { useState } from 'react';import './Style.css';         // CSS file for styleimport 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;
Step 6: Make a Child component by going on src folder->New File as shown and name it Child,js
Go to src->New File to create a new child component
Step 7: Write the following code in Child.js File
Child.js will have the following:
A message in the console which tells the child component is rendered,
Will return a div that has a heading that uses prop to get the name in it.
The code gives a message each time the component’s render function is called. Each time the count button is clicked state change is triggered. Each state change in the parent component triggers re-rendering of all its subsequent child components even if no props are changed.
Child.js
Javascript
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:
The number of times Parent component is re-rendered, the number of times the child component is also re-rendered can be seen in the console area. 
How to prevent unwanted re-rendering of components?
If the child component is re-rendered without any change in its props then it could be prevented by using hooks. React.memo is the savior, it is a higher-order component that memorize remembers) the result i.e. React will skip rendering of that component and reuse the last rendered result. It checks for prop changes.
Example: Minor changes in the Simple Counter React project can prevent our project from unwanted re-rendering. Changes need to be done in the Child.js file as shown below.
Javascript
import React from 'react';      function Child(props){    console.log("Child Rendered");    return(        <div>            <h1>Child Name={props.name}</h1>        </div>    );}  // Export default Child;  export default React.memo(Child); // Changes
Output:
Now the child component is not re-rendered on re-rendering of the parent component. Can be seen clearly in the console area.
Note: This method only exists as a performance optimization. Do not rely on it to prevent render, as this can lead to bugs.
Blogathon-2021
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components