2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh I think I get it. So refetch is in the deps in case this component is called from another parent component with a different refetch implementation, is that it?
that way onAddNewAccount will be recreated with the different refetch method
in case this component is called from another parent component with a different refetch implementation It's there in case refetch changes from one render to the next. For example, if the parent component rerenders and creates a new refetch function. that way onAddNewAccount will be recreated with the different refetch method Correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.