React-hooks React.memo 、 useMemo、 useCallback的使用区别

1:React.memo类似于PureComponent的作用,当父类传递的props发生变化时才会重新渲染

import React, { useState } from 'react';
import Child from '../Child';

function Parent() {
  const [parentCount, setParentCount] = useState(0);
  console.log('父組件重新渲染--------------');
  return (
    <div style={{ background: 'lightseagreen' }}>
      <Child />
      <button type="button" onClick={() => { setParentCount(parentCount + 1); }}>父组件 +1</button>
    </div>
  );
}

export default Parent;

import React from 'react';

function Child() {
  console.log('------------子組件重新渲染');
  return (
    <div style={{ background: 'pink', margin: '50px 0' }}>
      <button type="button">子組件</button>
    </div>
  );
}

export default React.memo(Child);

2:useMemo用于减少每次组件重新渲染时重复进行复杂的计算,参数为一个函数和可选的依赖项数组,返回传入函数的调用结果。当该方法用于子类时,需要配合React.memo使用

把一些涉及计算的方法放在useMemo方法中,避免无效计算

import React, { useState, useMemo } from 'react';
import Child from '../Child';

function Parent() {
  const [parentCount, setParentCount] = useState(0);
  const [otherCount, setOtherCount] = useState(0);
  console.log('父組件重新渲染--------------');

  // 一个复杂的计算
  const computedFn = (a, b) => {
    console.log('----重新执行了计算----');
    return a + b;
  };

  const computedValue = useMemo(() => {
    return computedFn(parentCount, 1);
  }, [parentCount]);
  
  return (
    <div style={{ background: 'lightseagreen' }}>
      <Child parentCount={parentCount} computedValue={computedValue} />
      <button type="button" onClick={() => { setParentCount(parentCount + 1); }}>父组件 +1</button>
      <button type="button" onClick={() => { setOtherCount(otherCount + 1); }}>父组件 otherCount+1</button>
    </div>
  );
}

3:useCallback用于需要传递给子组件的函数,减少子组件的重复渲染,参数为一个函数和可选的依赖项数组,返回出入函数的记忆版本。当该方法需要配合React.memo使用。

import React, { useState, useCallback } from 'react';

// ...other code

  const computedFn = useCallback(() => {
    console.log(parentCount);
    return parentCount + 1;
  }, [parentCount]) ;

// ...other code

export default Parent;
import React from 'react';

function Child(props) {
  const { computedValue, computedFn } = props;
  console.log('------------子組件重新渲染');
  return (
    <div style={{ background: 'pink', margin: '50px 0' }}>
      <div>
        父组件传入的计算结果:
        {computedValue}
      </div>
      <button type="button" onClick={computedFn}>子組件</button>
    </div>
  );
}

export default React.memo(Child);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值