0

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;
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Yos
  • 1,276
  • 1
  • 20
  • 40
  • not sure I understand what you are asking us...would you kindly edit your question and make it specific? – Peter Aug 30 '19 at 15:21
  • @Peter I think the question is very precise. Where do you find ambiguity in this question? – Yos Aug 30 '19 at 15:24

1 Answers1

1

It caches the callback itself plus the dependent values you passed as the second argument. At any point in time it holds one callback reference and one array of dependent values.

It needs the dependent values to check if it should create a new callback reference or not.

Nappy
  • 3,016
  • 27
  • 39