리액트 문서 읽기. useMemo / useCallback

null·2024년 2월 19일
0

react 공홈 읽기.

목록 보기
3/3

https://react.dev/reference/react/useMemo
https://react.dev/reference/react/useCallback

###useMemo
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.

React will call your function during the initial render. On next renders, React will return the same value again if the dependencies have not changed since the last render.

React will not throw away the cached value unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should be fine if you rely on useMemo solely as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.

리액트는 특정 이유가 없는 한 캐시된 값을 버리지 않습니다. 예를 들어, 개발 중에는 컴포넌트 파일을 편집할 때 캐시를 버립니다. 개발 및 프로덕션 모두에서 초기 마운트 중에 컴포넌트가 중단되면 리액트는 캐시를 버립니다. 미래에는 리액트가 캐시를 버리는 기능을 활용하는 더 많은 기능을 추가할 수 있습니다. 예를 들어, 리액트가 미래에 가상 목록을 내장 지원하는 기능을 추가한다면, 가상 테이블 뷰포트에서 스크롤되어 보이지 않는 항목에 대한 캐시를 버리는 것이 타당할 것입니다. 이것은 useMemo를 성능 최적화 용도로만 사용하는 경우에는 문제가 되지 않을 것입니다. 그렇지 않으면 상태 변수나 ref를 사용하는 것이 더 적절할 수 있습니다.

--> 이부분 잘 이해가 안 가는데 useMemo는 불필요하게 캐싱된 값을 가진다는 의미인건지..?

useMemo caches a calculation result between re-renders until its dependencies change.
다시 말해, useMemo는 종속성이 변경될 때까지 다시 렌더링 사이에 계산 결과를 캐시합니다.

Also, not all memoization is effective: a single value that’s “always new” is enough to break memoization for an entire component.
"항상 새로운" 단일 값이 있으면 컴포넌트 전체에 대한 메모이제이션을 깨뜨릴 수 있습니다.

Depending on an object like this defeats the point of memoization. When a component re-renders, all of the code directly inside the component body runs again. The lines of code creating the searchOptions object will also run on every re-render. Since searchOptions is a dependency of your useMemo call, and it’s different every time, React knows the dependencies are different, and recalculate searchItems every time.

My useMemo call is supposed to return an object, but returns undefined

  const searchOptions = useMemo(() => {
    matchMode: 'whole-word',
    text: text
  }, [text]);
  
    // This works, but is easy for someone to break again
  const searchOptions = useMemo(() => ({
    matchMode: 'whole-word',
    text: text
  }), [text]);

###useCallback
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
useMemo는 재렌더링 사이에서 계산 결과를 캐시하는 React Hook입니다.

useCallback is a React Hook that lets you cache a function definition between re-renders.
useCallback은 재렌더링 사이에서 함수 정의를 캐시하는 React Hook입니다.

export default function Page({ productId, referrer }) {
  const handleSubmit = useMemo(() => {
    return (orderDetails) => {
      post('/product/' + productId + '/buy', {
        referrer,
        orderDetails
      });
    };
  }, [productId, referrer]);

  return <Form onSubmit={handleSubmit} />;
}

export default function Page({ productId, referrer }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails
    });
  }, [productId, referrer]);

  return <Form onSubmit={handleSubmit} />;
}

위처럼 한 이유. 일단 useMemo는 빈 파라미터를 보내야 하니까!!! 이 부분 넘 중요하다.

useMemo: Caches the result of calling a function. It's useful when you want to memoize the result of a computation based on certain dependencies. React will call the function to recalculate the result only when necessary.

useCallback: Caches the function itself. It's handy when you want to memoize a callback function to prevent unnecessary re-renders of child components. The function will not be invoked until it's actually needed, typically when an event occurs.

useMemo: 함수 호출 결과를 캐시합니다. 특정 종속성에 따라 계산 결과를 메모이제이션하려는 경우 유용합니다. React는 필요할 때만 함수를 호출하여 결과를 다시 계산합니다.

useCallback: 함수 자체를 캐시합니다. 자식 컴포넌트의 불필요한 다시 렌더링을 방지하기 위해 콜백 함수를 메모이제이션하려는 경우 유용합니다. 함수는 실제로 필요할 때까지 호출되지 않습니다. 일반적으로 이벤트가 발생할 때 호출됩니다.

팀원들과 나눈 이야기
##useMemo

  • React will not throw away the cached value unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount.
    --> 이부분 잘 이해가 안 가는데 리액트가 특정 상황이 아니라면 캐시된 값을 버리지 않는다는건데 이게 useMemo의 특징인건지 리액트의 특징이란건지..?
    --> 이건 메모제이션의 특징이라고 보면 된다!!!
  • My useMemo call is supposed to return an object, but returns undefined..
    --> 이거 실수한적 있던 기억이 났음.

  • useMemo 쓸지 말지 비용이 비싼지 알고 싶을 땐, console.time을 이용하자.

  • calculation function은 pure 해야한다.

##useCallback

  • useCallback is a React Hook that lets you cache a function definition between re-renders.

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
함수를 호출하고 나온 결과를 캐싱하는 것이 useMemo useCallback은 함수 자체를 캐시 하는 차이가 있다.

  • 자식 컴포넌트의 불필요한 렌더링을 막고 싶다면 사용하기 좋다.

  • 다음상태를 계산하기 위해 상태를 읽는 경우, 대신 업데이트 함수를 전달하여 해당 dependency를 제거할 수 있다.

  • 커스텀 훅에서, 해당 Hook이 반환하는 모든 함수를 useCallback으로 래핑하는 것을 권장

  • useMemo는 함수의 결과값을 캐싱하고, useCallback은 함수 자체를 캐싱한다.

profile
개발이 싫어.

0개의 댓글