• 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)。

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

  • 相关阅读:
    IDEA 2022报错:Error running,Command line is too long. Shorten command line
    SSH在线考试系统
    自动驾驶学习笔记(十)——Cyber通信
    KMP算法详解以及Java代码实现
    Visual Studio 2022 版本 17.4 预览版 3 中对c++编译时优化的内容你都知道吗
    F检验临界值表(Frideman检验表)
    Python使用scapy库监听指定的网卡数据并转发
    deepstream·在python中安装pyds包
    neo4j 查询所有 label
    《C++新经典》第17章 并发与多线程
  • 原文地址:https://www.cnblogs.com/jiajialove/p/16595701.html