SoFunction
Updated on 2025-04-07

react component memo useMemo useCallback usage difference example

text

Memo is used to optimize the repetitive rendering behavior of function components, targeting a component

useMemo returns a memoized value

In essence, the same algorithm is used to determine whether the dependency has changed, and then decide whether to trigger the logic in memo or useMemo. Using memo can avoid unnecessary repeated calculations and reduce resource waste

useCallback returns a memoized function

useMemo and useCallback both receive two parameters. The first parameter is fn and the second parameter is []. The parameters that depend on the change in the array can be directly applied to the component, for example

    export default memo(Mycomponent)

The execution timing of useMemo and useEffect is inconsistent: useEffect executes side effects, so it must be executed after rendering. useMemo needs to have a return value, and the return value can directly participate in the rendering, so useMemo is completed during rendering.

Memo use

    // Parent component    const Parent = ()=>{
        const [count, setCount] = useState(1)
        const addCount = ()=>{
           setCount(count + 1)
        }
        return(
            <>
             <div onClick={addCount}>count: {count}</div>
             <Child />
            </>
        )
    }
    // Subcomponents    const Child = memo(()=>{
        ('child start---')
        return(
            <div>child...</div>
        )
    })
    // After using memo, the child component will not be rendered when the props or state of the child component does not change.

useMemo

   const sum = ()=>{
      return a+b
   }
   const result = useMemo(()=>{sum()},[a,b])
   // Execution of sum function will be triggered only when the value of a or b changes

useCallback

    // Parent component, pass name and changeName methods to child components    const Parent = () => {
      const [count, setCount] = useState(1);
      const [name, setName] = useState("bbz");
      const addCount = () => {
        setCount(count + 1);
      };
      const changeName = useCallback((n) => {
        setName(n);
      }, []);
      return (
        <>
          <div onClick={addCount}>count: {count}</div>
          <Child name={name} changeName={changeName} />
        </>
      );
    };
    // Subcomponents    const Child = ({ name, changeName }) => {
      ("child start---");
      return (
        <div
          onClick={() => {
            changeName("bobozai");
          }}
        >
          child comps: {name}
        </div>
      );
    };
    // If useCallback is not used, the child component will console render while clicking on the parent component count.    // Because the parent component will be re-rendered when updating count, resulting in a changeName function being regenerated.    // So the props of the subcomponent have changed, causing the subcomponent to be re-rendered    // And yeschangeNameFor functionsuseCallbackMake a parcel,Then cache the function will not be regenerated

The above is the detailed content of the use of react component memo useMemo useCallback. For more information about react component memo useMemo useCallback, please follow my other related articles!