When the state of the parent component changes, it causes the child component to re-render, resulting in a performance drain. In class components, it is commonly usedshouldComponentUpdateTo compare state and prevent repeated rendering of child components, used in hooksuseMemo

Code sample

  • Before using

    Each time the button is clicked to change the num of the parent component, the child component is rerendered, but the child component is not changed

    // The parent component comp1.js
    import React,{useState} from 'react';
    import Child from './Child';
    function Comp1(){
      const [count,setCount] = useState(0);
      const [num,setNum] = useState(0);
      return (
        <div>
          <p>{num}</p>
          <button onClick={()= >{setNum(num+1)}}> The parent component uses value modification alone</button>
          <p>{count}</p>
          <button onClick={()= >{setCount(count+1)}}> Change the parent/child public value</button>
    
          <Child count={count} />
        </div>)}export default Comp1;
    
    
    // Child component child.js
    import React from 'react';
    function Child(props){
      function workingCount(){
        console.log('Child component function fires');
        return props.count+'_child'
      }
      let child_count = workingCount();
      return (
        <div> <div>{child_count}</div> </div>)}export default Child;
    
    //index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import Comp1 from './Comp1';
    ReactDOM.render(<Comp1 />.document.getElementById('root'));
    Copy the code
    • After using
    // All other files are the same except child.js
    import React,{useMemo} from 'react';
    function Child(props){
      function workingCount(){
        console.log('Child component function fires');
        return props.count+'_child'
      }
      Function (){},[])
      // useMome accepts two parameters
      // The first is a function that does not want to be called
      // The second is an array in which changes in the value trigger the function in the first argument
      let child_count = useMemo(() = >(workingCount()),[props.count]); 
      return (
        <div>
          <div>{child_count}</div>
        </div>)}export default Child;
    Copy the code