简体   繁体   中英

React useCallback setting dependency on a function called inside the callback

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.

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.

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