简体   繁体   中英

React useMemo and useCallback

I have doubts about the usage of useMemo and 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?

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?

Thanks!

  1. No need to use useCallback because no need to make it a function itself. 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. With useCallback on the above code you are only saving the execution time of the function definition. 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 (
   <div>
    {renderedJSX}
   </div>
);

That way you are better of creating a new Component which takes elements as a prop and start using React.memo .

No matter which one you use you ( useCallback or useMemo ), you will have to use elements as a dependency. Once elements change your code will rerun. elements is an array so it will change in every render.

  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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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