Home > Software engineering >  React useCallback setting dependency on a function called inside the callback
React useCallback setting dependency on a function called inside the callback

Time:11-26

I'm working on a web app using react and saw this implemented there. It goes something like this:

const onAddNewAccount = useCallback(async () => {
   await refetch();
   setOtherState((prev) => {...});
},
[refetch]);

I don't understand why do this, is this actually something correct? Because from what I understand the callback will be called on one of the dependencies changing.

From what I've seen calling refetch won't actually trigger useCallback probably because it is just called right? not changed.

So basically I need help understanding why they did this.

CodePudding user response:

the callback will be called on one of the dependencies changing.

No, it won't be called, it will just be recreated. The purpose of useCallback is to memoize the function and reuse it if nothing has changed. In other words, it's trying to make it so onAddNewAccount from render 1 === onAddNewAccount from render 2.

If refetch changes, then the memoization will break and a new function is created. That way the new onAddNewAccount can call the new refetch if needed. If refetch never changes, then that's great: the memoization can last forever then.

  • Related