首页  >  文章  >  web前端  >  useMemo的源码:

useMemo的源码:

Patricia Arquette
Patricia Arquette原创
2024-10-04 18:21:31964浏览

The source code of useMemo:

有两种情况:mount和update,所以useMemo有两种实现:mountMemoupdateMemo

  • mountMemo源码:

function mountMemo<T>(
  nextCreate: () => T,
  deps: Array<mixed> | void | null,
): T {
  const hook = mountWorkInProgressHook();
  const nextDeps = deps === undefined ? null : deps;
  const nextValue = nextCreate();
  if (shouldDoubleInvokeUserFnsInHooksDEV) {
    setIsStrictModeForDevtools(true);
    nextCreate();
    setIsStrictModeForDevtools(false);
  }
  hook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}


说明
在挂载阶段,useMemo函数调用回调函数计算并返回值。将值和依赖项保存到 hook.memoizedState 中。

  1. 使用 mountWorkInProgressHook 创建钩子对象。

  2. 将 deps 保存在 nextDeps 中。

  3. 调用nextCreate()获取nextValue。如果在开发环境中,请调用两次。

  4. 将 nextValue 和 nextDeps 保存在 hook.memoizedState 中并返回 nextValue。

  • updateMemo的源代码:

function updateMemo<T>(
  nextCreate: () => T,
  deps: Array<mixed> | void | null,
): T {
  const hook = updateWorkInProgressHook();
  const nextDeps = deps === undefined ? null : deps;
  const prevState = hook.memoizedState;
  // Assume these are defined. If they're not, areHookInputsEqual will warn.
  if (nextDeps !== null) {
    const prevDeps: Array<mixed> | null = prevState[1];
    if (areHookInputsEqual(nextDeps, prevDeps)) {
      return prevState[0];
    }
  }
  const nextValue = nextCreate();
  if (shouldDoubleInvokeUserFnsInHooksDEV) {
    setIsStrictModeForDevtools(true);
    nextCreate();
    setIsStrictModeForDevtools(false);
  }
  hook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}


说明
在更新阶段,React 会判断 deps 是否发生变化,如果发生变化,React 将运行回调以获取新值并返回。如果不更改,React 将返回旧值。

  1. 获取新的钩子对象:hook = updateWorkInProgressHook();
  2. 如果 deps 数组为空 if (nextDeps !== null),则每次渲染时调用回调函数并返回新值。
  3. 如果deps数组不为空,则判断deps是否发生变化 if (areHookInputsEqual(nextDeps, prevDeps))。如果没有改变,则返回旧值 return prevState[0];.

以上是useMemo的源码:的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn