面试那些事React那些事

useMemo和useCallback到底干了啥

2022-02-06  本文已影响0人  _静夜听雨_

在React hooks使用过程中,我们知道useMemo是用来缓存值,useCallback用来缓存函数,但具体如何实现?看了源码,一目了然。。。

useMemo

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];
            } 
        }
    }
    const nextValue = nextCreate();
    hook.memoizedState = [nextValue, nextDeps];
    return nextValue;
}

useCallback

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;
}
上一篇 下一篇

猜你喜欢

热点阅读