[英]What is the cache size of useCallback and useMemo react hook and why?
I'm looking at React source code and specifically at useCallback
implementation.我正在查看 React 源代码,特别是
useCallback
实现。 As far as I understand the cache size of useCallback
is one.据我了解
useCallback
的缓存大小是一。 In mountCallback
we initialize hook.memoizedState
to an array where the first element is the callback
- the first parameter to useCallback
.在
mountCallback
我们将hook.memoizedState
初始化为一个数组,其中第一个元素是callback
- useCallback
的第一个参数。 In updateCallback
if the dependencies didn't change then we return the first element of the hook.memoizedState
array.在
updateCallback
如果依赖项没有改变,那么我们返回hook.memoizedState
数组的第一个元素。 Because the callback
's reference didn't change there will not be a re-rendering.因为
callback
的引用没有改变,所以不会重新渲染。 Conversely, if the dependencies changed and we set the first element of hook.memoizedState
array to the callback
parameter of updateCallback
then callback
's reference will change (because function object parameters always have a new value), therefore triggering re-rendering.相反,如果依赖项发生变化并且我们将
hook.memoizedState
数组的第一个元素设置为updateCallback
的callback
参数,则callback
的引用将发生变化(因为函数对象参数始终具有新值),从而触发重新渲染。
So caching in useCallback
is based on the callback
's reference.所以
useCallback
中的缓存是基于callback
的引用。 Is my understanding correct?我的理解正确吗?
function mountCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
const hook = mountWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
hook.memoizedState = [callback, nextDeps];
return callback;
}
function updateCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
const hook = updateWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
hook.memoizedState = [callback, nextDeps];
return callback;
}
It caches the callback
itself plus the dependent values you passed as the second argument.它缓存
callback
本身以及您作为第二个参数传递的依赖值。 At any point in time it holds one callback
reference and one array of dependent values.在任何时候,它都持有一个
callback
引用和一个依赖值数组。
It needs the dependent values to check if it should create a new callback reference or not.它需要依赖值来检查它是否应该创建一个新的回调引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.