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!
useCallbackbecause no need to make it a function itself. The cleaner way to write this should be :But in any case:
useMemois for values first of all anduseCallbackfor function definition. WithuseCallbackon 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:And then use it with your return statement:
That way you are better of creating a new Component which takes
elementsas a prop and start usingReact.memo.No matter which one you use you (
useCallbackoruseMemo), you will have to useelementsas a dependency. Once elements change your code will rerun.elementsis an array so it will change in every render.memoizeif you want to usinguseMemobut 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.