简体   繁体   English

React - 如何用 useMemo 替换 useCallback 钩子?

[英]React - how to replace useCallback hook with useMemo?

I am reading this article about memoization in React, and I wonder how can I translate and use useMemo instead of useCallback hook.我正在阅读这篇关于 React 中的记忆化的文章,我想知道如何翻译和使用useMemo而不是useCallback钩子。 In particular for this example:特别是对于这个例子:

<Child name={ useCallback(() => {console.log('Really Skinny Jack')}, [])  } />

Where Child component looks like this:子组件看起来像这样:

export default React.memo(function Child({ name }) {
  console.log("Child component");
  return (
    <>
      {name()}
      <div>Child component</div>
    </>
  );
});

If I try to replace this with useMemo :如果我尝试用useMemo替换它:

  <Child
    name={useMemo(() => {
      console.log("useMemo");
    }, [])}
  />

I get an error:我得到一个错误:

TypeError name is not a function

I also tried like this:我也试过这样的:

  {useMemo(
    <Child
      name={() => {
        console.log("useMemo");
      }}
    />,
    []
  )}

But, then I get:但是,然后我得到:

TypeError nextCreate is not a function

So, I how am I suppose to replace useCallback with useMemo in this example?那么,在这个例子中,我该如何用useMemo替换useCallback呢?

With useMemo , you can do it like this使用useMemo ,你可以这样做

<Child
  name={useMemo(() => {
    // return the function or anything you want react to memoize
    return () => {
      console.log('useMemo');
    };
  }, [])}
/>

With useMemo , whatever you return from the useMemo 's callback will be memoized.使用useMemo ,无论你从useMemo的回调中返回什么,都会被记住。 On the other hand, useCallback is used to memoize functions only.另一方面, useCallback仅用于记忆函数。

Some key differences to note需要注意的一些关键差异

useMemo

Used to memoize functions, arrays, objects, etc.用于记忆函数、arrays、对象等。

const memoizedList = useMemo(() => {
  return [1, 2, 3];
}, []);

const memoizedFunction = useMemo(() => {
  return () => {
    console.log('I am meoized');
  };
}, []);

useCallback

Used to memoize functions用于记忆函数

const memoizedFunction = useCallback(() => {
  console.log('I am meoized');
}, []);

React.memo

A Higher-Order Component to memoize React components用于记忆 React 组件的高阶组件

const MyComponent = (props) => {
  return "I am a memoized component";
}
export default React.memo(MyComponent);

Try to replace it like this尝试像这样替换它

<Child name={React.useMemo(() => () => alert(55), [])} />

So, I how am I suppose to replace useCallback with useMemo in this example?那么,在这个例子中,我该如何用 useMemo 替换 useCallback 呢?

The useCallback hook returns a memoized callback function that is passed to it whereas the useMemo hook takes a function callback and returns a memoized value. useCallback钩子返回传递给它的记忆回调 function,而useMemo钩子接受 function 回调并返回记忆值。

From theuseCallback docs:来自useCallback文档:

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps) . useCallback(fn, deps)等同于useMemo(() => fn, deps)

The following are equivalent implementations:以下是等效的实现:

  1. useCallback

     const nameHandler = useCallback(() => { console.log('Really Skinny Jack'); }, []); ... <Child name={nameHandler} />
  2. useMemo

     const nameHandler = useMemo(() => () => { console.log('Really Skinny Jack'); }, []); ... <Child name={nameHandler} />

The useMemo hook is taking a callback that returns a function that is being used and passed as a callback to a child component. useMemo挂钩正在接受一个回调,该回调返回一个 function,该回调被使用并作为回调传递给子组件。

It isn't really clear at all why you would want to do this though.但是,您为什么要这样做还不是很清楚。 The useCallback hook is the intended hook to be used when you want to memoize a callback that is passed to children components. useCallback挂钩是当您想要记住传递给子组件的回调时使用的预期挂钩。 It's also a lot clearer and easier to read than the "double" function that is used in the useMemo version.它也比useMemo版本中使用的“双重”function 更清晰易读。 I suggest sticking to the useCallback version of your code.我建议坚持使用代码的useCallback版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM