I have a parent componenet, Inside this I have included a child component with props. but When any state is changed in parent component (that doesn't related to child component) then child component re-render. I don't want this re render on every state change. Can we stop?
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Child from "./child";
import "./styles.css";
function App() {
const [any_state, setAnyState] = useState(false);
const handleClick = () => {
setAnyState(!any_state);
};
return (
<div className="App">
Parent Page ({any_state ? "true" : "false"})
<br />
<button onClick={handleClick}>Click me</button>
<Child data={"any data"} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
child.js
import React from "react";
function Child(props) {
console.log("child component");
return <div className="App">child Page</div>;
}
export default Child;
https://codesandbox.io/s/clever-oskar-fpxm3?fontsize=14
I don't want "child component" to be displayed in console on every state change.
1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
React shouldComponentUpdate is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. Only use this method if when a component will stay static or pure. The React shouldComponentUpdate method requires you to return a boolean value.
If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.
In function components, the execution of the whole function is the equivalent of the render function in class components. When the state changes in the parent component (in this case, App ), the two Tile components will re-render, even though the second one doesn't even receive any props.
You want to use React.memo
for this. Read more here.
This will prevent re-renders when props did not change.
Instead of export default Child;
use export default React.memo(Child);
in your child.js
.
import React from "react";
function Child(props) {
console.log("child component");
return <div className="App">child Page</div>;
}
export default React.memo(Child);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With