简体   繁体   English

反应 useMemo 和 useCallback

[英]React useMemo and useCallback

I have doubts about the usage of useMemo and useCallback我对useMemo和useCallback的用法存疑

const componentName = () => {

...

const renderItems = () => elements.map(elem => <div> {elem.name} </div>

...
return (
   <div>
    {renderItems()}
   </div>
);
}

The first one is: Should I use the hook useCallback in the function renderItems?第一个是:我应该在函数 renderItems 中使用钩子 useCallback 吗?

The other question is in the case that I have an external file that exports a constant:另一个问题是我有一个导出常量的外部文件:

export const labels = ["label1", "label2", "label3"];

Should I use the hook useMemo on the variable labels that are located in a different file from the component?我应该在与组件位于不同文件中的变量标签上使用钩子 useMemo 吗?

Thanks!谢谢!

  1. No need to use useCallback because no need to make it a function itself.不需要使用useCallback因为不需要使它本身成为一个函数。 The cleaner way to write this should be:更简洁的写法应该是:
return (
   <div>
    {elements.map(elem => <div> {elem.name} </div>}
   </div>
);

But in any case: useMemo is for values first of all and useCallback for function definition.但无论如何: useMemo首先用于值, useCallback用于函数定义。 With useCallback on the above code you are only saving the execution time of the function definition.在上面的代码中使用useCallback只是节省了函数定义的执行时间。 The function will still run.该功能仍将运行。 If you want to memoize, you can memoize the output so the function runs only once like this:如果你想记忆,你可以记忆输出,这样函数只运行一次,如下所示:

const renderedJSX = useMemo(() => 
{
const val = elements.map(elem => <div> {elem.name}</div>);
return val;
},[elements]);

And then use it with your return statement:然后将它与您的 return 语句一起使用:

return (
   <div>
    {renderedJSX}
   </div>
);

That way you are better of creating a new Component which takes elements as a prop and start using React.memo .这样你最好创建一个将elements作为道具的新组件并开始使用React.memo

No matter which one you use you ( useCallback or useMemo ), you will have to use elements as a dependency.无论您使用哪一个( useCallbackuseMemo ),您都必须使用elements作为依赖项。 Once elements change your code will rerun.一旦元素更改,您的代码将重新运行。 elements is an array so it will change in every render. elements是一个数组,因此它会在每次渲染时发生变化。

  1. If the variables are scoped only to the react component you can keep them inside the function body.如果变量的范围仅限于反应组件,您可以将它们保留在函数体内。 memoize if you want to using useMemo but that would be over kill for such a simple variable. memoize如果你想使用useMemo但这对于这样一个简单的变量来说就太过分了。 Even if it is declared in a separate file, the code will only run once when it is parsed, so you don't have to worry about it.即使在单独的文件中声明,代码在解析时也只会运行一次,因此您不必担心。

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

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