[英]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.我正在使用 react 开发 web 应用程序,并看到它在那里实现。 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?从我所见,调用
refetch
实际上不会触发useCallback
可能是因为它只是被调用了吗? 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. useCallback
的目的是记住 function 并在没有任何变化的情况下重用它。 In other words, it's trying to make it so onAddNewAccount
from render 1 === onAddNewAccount
from render 2.换句话说,它试图从渲染 1 的
onAddNewAccount
=== 来自渲染 2 的onAddNewAccount
做到这一点。
If refetch
changes, then the memoization will break and a new function is created.如果
refetch
更改,则 memoization 将中断并创建一个新的 function。 That way the new onAddNewAccount
can call the new refetch if needed.这样,新的
onAddNewAccount
可以在需要时调用新的重新获取。 If refetch
never changes, then that's great: the memoization can last forever then.如果
refetch
永远不会改变,那就太好了:memoization 可以永远持续下去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.