"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > useMemo의 소스 코드:

useMemo의 소스 코드:

2024-11-08에 게시됨
검색:731

The source code of useMemo:

마운트와 업데이트라는 두 가지 상황이 있으므로 useMemo에는 mountMemoupdateMemo.

라는 두 가지 구현이 있습니다.
  • mountMemo:
  • 의 소스 코드

function mountMemo(
  nextCreate: () => T,
  deps: Array | 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 함수는 콜백 함수를 호출하여 값을 계산하고 반환합니다. 값과 deps를 Hook.memoizedState.

에 저장하세요.
  1. mountWorkInProgressHook를 사용하여 후크 객체를 생성합니다.

  2. nextDeps에 deps를 저장합니다.

  3. nextCreate()를 호출하여 nextValue를 얻습니다. 개발 환경에서는 두 번 호출하세요.

  4. hook.memoizedState에 nextValue와 nextDeps를 저장하고 nextValue를 반환합니다.

  • updateMemo:
  • 의 소스 코드

function updateMemo(
  nextCreate: () => T,
  deps: Array | 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 | 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 배열이 비어 있는 경우(nextDeps !== null), 렌더링할 때마다 콜백 함수를 호출하고 새 값을 반환합니다.
  3. deps 배열이 비어 있지 않으면 (areHookInputsEqual(nextDeps, prevDeps))인 경우 deps가 변경되었는지 여부를 판단합니다. 변경되지 않은 경우 이전 값을 반환합니다. return prevState[0];.
릴리스 선언문 본 글은 https://dev.to/clara1123/the-source-code-of-usememo-5akk?1 에서 복제하였습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제해 주시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3