React中useMemo与useCallback的区别

useMemo

把“创建”函数和依赖项数组作为参数传⼊入useMemo,它仅会在某个依赖项改变时才重新计算memoized 值。这种优化有助于避免在每次渲染时都进⾏行行⾼高开销的计算。

importReact, { useState, useMemo } from"react";
export default functionUseMemoPage(props) {
    const [count, setCount] =useState(0);
    constexpensive=useMemo(() => {
        console.log("compute");
        let sum=0;
        for (leti=0; i) {
            sum+=i;
        }
        return sum;//只有count变化,这⾥里里才重新执⾏行行
      }, [count]);
    const [value, setValue] =useState("");
    return (

UseMemoPage

expensive:{expensive}

{count}


  
  setValue(event.target.value)} />
); }

useCallback

把内联回调函数及依赖项数组作为参数传⼊入useCallback,它将返回该回调函数的 memoized 版本,该回调函数仅在某个依赖项改变时才会更更新。当你把回调函数传递给经过优化的并使⽤用引⽤用相等性去避免⾮非必要渲染(例例如shouldComponentUpdate)的⼦子组件时,它将⾮非常有⽤用

importReact, { useState, useCallback, PureComponent } from"react";
export default function UseCallbackPage(props) {
    const [count, setCount] =useState(0);
    const addClick=useCallback(() => {
    let sum=0;
    for (leti=0; i) {
        sum+=i;    
    }
    return sum;  
    }, [count]);
    const [value, setValue] =useState("");
    return (
    

UseCallbackPage


  

{count}


  setCount(count+1)}>add
  setValue(event.target.value)} />
  
);
}
  class ChildextendsPureComponent {
    render() {
      console.log("child render");
      const { addClick } =this.props;

      return (
        

Child


        console.log(addClick())}>add

     )
  }
}

useCallback(fn, deps)相当于useMemo(() => fn, deps)。

注意依赖项数组不不会作为参数传给“创建”函数。虽然从概念上来说它表现为:所有“创建”函数中引⽤用的值都应该出现在依赖项数组中。未来编译器器会更更加智能,届时⾃自动创建数组将成为可能。

文章来源于互联网:React中useMemo与useCallback的区别

THE END
分享
二维码