[英]Is it more performant to use the dependencies of a React `useCallback` hook as arguments of the callback?
Suppose I have a callback function in React which uses variables a
, b
, and c
.假设我在 React 中有一个回调 function ,它使用变量
a
、 b
和c
。 I want to know the best way to make use of the useCallback
hook.我想知道使用
useCallback
钩子的最佳方法。
I can create a callback which takes no arguments and use [a,b,c]
as the dependencies array.我可以创建一个不接受 arguments 的回调,并使用
[a,b,c]
作为依赖项数组。
const onMutate = useCallback( () => {~~~~} , [a,b,c] )
~~~~ onPress={onMutate}
Or I can create a callback which takes arguments (a,b,c)
and has an empty dependency array.或者我可以创建一个回调,它采用 arguments
(a,b,c)
并且有一个空的依赖数组。
const onMutate = useCallback( (a,b,c) => { ~~~~} , [] )
~~~~ onPress={() => onMutate(a,b,c)}
In the former, the callback function is newly created each time, but there is no anonymous function in onPress.前者每次新建回调function,但onPress中没有匿名function。
In the latter, the callback function is created only once, but an anonymous function is created in onPress each time.在后者中,回调 function 只创建一次,但每次在 onPress 中都会创建一个匿名的 function。
Which case is better?哪种情况更好?
First keep in mind: Using useCallback
is not always a good case, as Kent C.首先要记住:使用
useCallback
并不总是一个好的案例,例如 Kent C。 Dodds says .多兹说。
However, if you really wanna go with useCallback
it also only makes sense, when the value in useCallback
is memoized.但是,如果您真的想要 go 和
useCallback
,那么只有在useCallback
中的值时才有意义。 See this one CodeSandbox: https://codesandbox.io/s/quizzical-dawn-glqlg看这个CodeSandbox: https://codesandbox.io/s/quizzical-dawn-glqlg
That being said, if you are sure to use useCallback
it doesn't matter, which way you are going, because in the very best case, all three of those variables are being memoized in the first run.话虽如此,如果您确定要使用
useCallback
,那么您将采用哪种方式并不重要,因为在最好的情况下,所有这三个变量都会在第一次运行时被记忆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.