When the parent component is re-rendered, for example when updating the state of itself or so.
When the props of child component are re-rendered.
But actually, it is only needed when props are rendered to re-render the child component. Everything else is unnecessary.
・src/Example.js
mport React, { useState } from "react"; import Child from "./Child"; import "./Example.css"; const Example = () => { console.log("Parent render"); const [countA, setCountA] = useState(0); const [countB, setCountB] = useState(0); return ( <div className="parent"> <div> <h3>Parent Component</h3> <div> <button onClick={() => { setCountA((pre) => pre + 1); }} > Button A </button> <span>Update the state of Parent Component</span> </div> <div> <button onClick={() => { setCountB((pre) => pre + 1); }} > Buton B </button> <span>Update the state of Child Component</span> </div> </div> <div> <p>The count of clicked:{countA}</p> </div> <Child countB={countB} /> </div> ); }; export default Example;
・src/Child .js
const Child = ({ countB }) => { console.log("%cChild render", "color: red;"); return ( <div className="child"> <h2>Child component</h2> <span>The count of B button cliked:{countB}</span> </div> ); }; export default Child;
・Like this.
・src/Child .js (using a memo hook)
import { memo } from "react"; function areEqual(prevProps, nextProps) { if (prevProps.countB !== nextProps.countB) { return false; // re-rendered } else { return true; // not-re-rendred } } const ChildMemo = memo(({ countB }) => { console.log("%cChild render", "color: red;"); return ( <div className="child"> <h2>Child component</h2> <span>The count of B button cliked:{countB}</span> </div> ); }, areEqual); export default ChildMemo;
・Like this.
The above is the detailed content of React Basics~Render Performance/ memo. For more information, please follow other related articles on the PHP Chinese website!