When we renders multiple child component inside a Parent component in a functional react component. So whenever Parent component will re-render it will also re-render child components as well.
Re-rendering of child components in each and every parent render will cause the performance issues in our application. We will see how can we avoid these unnecessary re-renders below.
Let's take an example -
App.js
import { useEffect, useState } from "react";
import Child from "./Child";
import "./styles.css";
export default function App() {
const [num, setNum] = useState(0);
useEffect(() => {
setNum((num) => num + 1);
}, []);
return (
<div className="App">
<h1>{num}</h1>
<Child />
</div>
);
}
Child.js
import React from "react";
const Child = () => {
console.log("rendered");
return <h1>test</h1>;
};
export default Child;
So let's see what is happening here.
We have a parent component (App.js). Where we are rendering Child.js (our child component). So when we will run this application It will render once and useEffect hook will execute and it will sets the state of the component. That will cause another re-render.
With both the re-renders Child component will also re-renders twice.
To see that we can see the console will be logged twice.
To avoid this behavior we need to wrap up our child component inside React.memo.
So our new Child Component will look like this now -
import React from "react";
const Child = React.memo(() => {
console.log("rendered");
return <h1>test</h1>;
});
export default Child;
Visit the below link for the live demo.
Comments
Post a Comment