1

I created a react app, in which I have a list of items with delete action. I know that if i pass this delete action from parent (the items container) , i can use "useCallback" in the parent to prevent unneeded recreations of the delete method.

But, what will happen if ill define the delete method in the item component and use "useCallback" in it? wont it work? wont it use the same memorized method without creating each time a new one?

in other words, what is the scope of the memorization? is it global? or per component?

pseudo code:

function ListComponent(){
  let arr = [1,2,3]
  return <div>
    {
      arr.map(item => <Item id={item} />
    }
  </div>
}

function Item({id}){
  let memorizedDelete = useCallback(() => alert("deleting"))
  return <div onClick={memorizedDelete} >  {id} </div>
}

thnx

eyal gromzin
  • 155
  • 2
  • 11
  • Note that calling `useCallback` without a dependency array the way you're doing here means the function isn't memoized. See: https://stackoverflow.com/a/55027723/882638 – ericgio Jan 27 '21 at 08:10
  • The way your example code is written, a separate memoized function will be created for each instance of `Item`. – ericgio Jan 27 '21 at 08:12

1 Answers1

0

What is the scope of the memorization? is it global? or per component?

It definitely is not global.

React hooks are only valid in the body of functional components or other react hooks. The scope would then be limited to the body of a functional component, or the body of the function defining a custom hook.

Component Scope

const MyFunctionalComponent = () => {
  const memoizedCallback = useCallback(() => expensiveFn(...args), [...args]);
  // memoizedCallback enclosed in scope of MyFunctionalComponent
};

Hook Function Scope

const useMyCustomHook = (arg, deps) => {
  // other hooks and logic
  const memoizedCallback = useCallback(() => expensiveFn(...args), [...args]);
  // memoizedCallback enclosed in scope of useMyCustomHook
};

Note: A custom hook can return the memoized callback, so its scope is still basically limited to that of the component instantiating the react hook.

But, what will happen if I'll define the delete method in the item component and use "useCallback" in it? wont it work? wont it use the same memorized method without creating each time a new one?

This will create a memoized callback that is only passed to a single child, there's really no benefit here other than if the mapped array is updated then the callback won't need to be recreated.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181