2

Let's say there is a function inside a component, for example like this:

     const MyComponent = ({data}) => {
       const myFunction = a => a+1;
       return <div>
                  data.map(num => myFunction(num))
              </div>
     }

I don't want myFunction() to be called again if it already has been called with the same argument. What is the best practice to add caching here?

Anna
  • 2,911
  • 6
  • 29
  • 42

1 Answers1

0

No, useCallback and useMemo have different purposes in this specific case read here, you need to create some cache mechanism yourself or take one from 3rd party package:

const MyComponent = ({data}) => {
  const cacheRef = React.useRef({})
  const myFunction = a => {
    const cache = cacheRef.current;
    if(cache[a]){
      return cache[a];
    } else{
      cache[a] = a+1;
      return cache[a];
    }
  };
  return <div>
          {data.map(num => myFunction(num))}
         </div>
}
gadi tzkhori
  • 574
  • 2
  • 13