Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reack Hooks - useMemo/useCallback #53

Open
imfenghuang opened this issue Jul 6, 2024 · 0 comments
Open

Reack Hooks - useMemo/useCallback #53

imfenghuang opened this issue Jul 6, 2024 · 0 comments

Comments

@imfenghuang
Copy link
Owner

imfenghuang commented Jul 6, 2024

挂载 mount

从挂载阶段来说,传入 useMount(() => T, deps) 的第一个参数(函数)会被执行一次,执行结果会被存储在 hook.memoizedState 中,同时返回该计算结果。

useCallback(fn, deps) 则直接将传入第一个参数(函数)存储进 hook.memoizedState,并返回该参数。

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 mountMemo<T>(
  nextCreate: () => T,
  deps: Array<mixed> | void | null,
): T {
  const hook = mountWorkInProgressHook();
  const nextDeps = deps === undefined ? null : deps;
  // 注意这里的计算,执行了一次 nextCreate 这个函数
  const nextValue = nextCreate();
  // 注意这里存储的值
  hook.memoizedState = [nextValue, nextDeps];
  // 注意这里返回的值
  return nextValue;
}

更新 update

update 时,两者也基本是一致的,如果依赖没有变化,则返回缓存的状态,即返回 hook.memoizedState 这个数组里的第一个值(即索引值为 0 的状态),如果依赖变化了,则 useMemonextValue 的存储和返回上,同 mount 时一样,执行一次函数,记录这个函数执行的结果,并返回,而 useCallback 缓存当次更新传入的 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;
}

function updateMemo<T>(
  nextCreate: () => 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];
      }
    }
  }

  // 注意这里的计算,执行了一次 nextCreate 这个函数
  const nextValue = nextCreate();
  // 注意这里存储的值
  hook.memoizedState = [nextValue, nextDeps];
  // 注意这里返回的值
  return nextValue;
}

判断 hook 的依赖是否相等,见 areHookInputsEqual #48

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant