This article has participated in the “Newcomer Creation Ceremony” activity, and started the road of digging gold creation together.

UseMemo and useCallback are two hooks optimized for performance in React hooks. Both hooks are executed when the component is first loaded and again when it changes based on its dependencies,

Difference between useMemo and useCallback

UseMemo caches variables, useCallback caches functions

1. UseMemo usage scenarios:

When the parent component updates A state state, it will render all its child components. Obviously, the performance is not optimal. When state A changes, only the child components that depend on state A will be re-rendered, and the other child components do not need to be re-rendered. Only when dependencies change is it re-rendered to achieve a cached effect

export default function Memo() {
    const [count, setCount] = useState(2);
    const [value, setValue] = useState('11');
    const finallyCount = useMemo(() = > {
        console.log('code shu');
        let sum = 0;
        for (let i = 0; i < count * 999; i++) {
            sum += i;
        }
        return sum;
    }, [count]);
 
    return <div>
        <h4>{count}-{finallyCount}</h4>
        {value}
        <div>
            <button onClick={()= > setCount(count + 1)}>+c1</button>
            <input value={value} onChange={event= > setValue(event.target.value)}/>
        </div>
    </div>;
}
Copy the code

Execution Result:In this example, finallyCount is initialized once, and setCount is initialized once, printing the Code SHU, but the code SHU is not printed when setValue changes the value as it enters the value in the input box

2. Usage scenarios of useCallback:

When the parent component needs to pass a changeAge function to the child component via props, the child component calls the changeAge method to pass the parent component. The parent component changes the age value and wraps the method in useCallback (). A cache function that is called only when a child component is triggered to change the age button. So when the name button that changes irrelevant data is clicked, the changeAge function does not execute

If you don’t use useCallback, every time you click the change irrelevant data name button, the parent component will execute a method passed to the child component. The child component will need to be wrapped with React. Memo, otherwise the performance optimization won’t take effect

export default function TestCallback() {
  const [name, setName] = useState("code shu");
  const [age, setAge] = useState(24);
  const changeAge = useCallback(() = > {
    setAge((age) = > age + 1); } []);console.log("TestCallback");
  return (
    <div>
      <div>name:{name}</div>
      <br />
      <button onClick={()= >SetName ((name) => name + 5)}> Change the irrelevant data name</button>
      <br />
      <br />
      <Age age={age} changeAge={changeAge} />
    </div>
  );
}

const Age = memo(function Message({ age, changeAge }: any) {
  console.log("age");
  return (
    <div>
      <button onClick={changeAge}>Change the age</button>
      <p>age:{age}</p>
    </div>
  );
});

Copy the code
  1. Click the Change Age button

2. Click on theChange the irrelevant data name button

If the text is wrong, hope big guy corrects