I'm looking at React source code and specifically at useCallback
implementation. As far as I understand the cache size of useCallback
is one. In mountCallback
we initialize hook.memoizedState
to an array where the first element is the callback
- the first parameter to useCallback
. In updateCallback
if the dependencies didn't change then we return the first element of the hook.memoizedState
array. Because the callback
's reference didn't change there will not be a re-rendering. 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.
So caching in useCallback
is based on the callback
's reference. 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;
}