Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So basically I need help understanding why they did this.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading