What's the difference between useCallback and useMemo in practice? Ask Question

What's the difference between useCallback and useMemo in practice? Ask Question

Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.

I passed inputs - as a second argument to useCallback - non-ever-changeable constants - but returned memoized callback still runs my expensive calculations at every render (I'm pretty sure - you can check by yourself in the snippet below).

I've changed useCallback to useMemo - and useMemo works as expected — runs when passed inputs changes. And really memoizes the expensive calculations.

Live example:

'use strict';

const { useState, useCallback, useMemo } = React;

const neverChange = 'I never change';
const oneSecond = 1000;

function App() {
  const [second, setSecond] = useState(0);
  
  // This �� expensive function executes everytime when render happens:
  const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
  const computedCallback = calcCallback();
  
  // This �� executes once
  const computedMemo = useMemo(() => expensiveCalc('useMemo'), [neverChange]);
  
  setTimeout(() => setSecond(second + 1), oneSecond);
  
  return `
    useCallback: ${computedCallback} times |
    useMemo: ${computedMemo} |
    App lifetime: ${second}sec.
  `;
}

const tenThousand = 10 * 1000;
let expensiveCalcExecutedTimes = { 'useCallback': 0, 'useMemo': 0 };

function expensiveCalc(hook) {
  let i = 0;
  while (i < tenThousand) i++;
  
  return ++expensiveCalcExecutedTimes[hook];
}


ReactDOM.render(
  React.createElement(App),
  document.querySelector('#app')
);
<h1>useCallback vs useMemo:</h1>
<div id="app">Loading...</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

ベストアンサー1

TL;DR;

  • useMemo is to memoize a calculation result between a function's calls and between renders
  • useCallback is to memoize a callback itself (referential equality) between renders
  • useRef is to keep data between renders (updating does not fire re-rendering)
  • useState is to keep data between renders (updating will fire re-rendering)

Long version:

useMemo focuses on avoiding heavy calculation.

useCallback focuses on a different thing: it fixes performance issues when inline event handlers like onClick={() => { doSomething(...); } cause PureComponent child re-rendering (because function expressions there are referentially different each time)

This said, useCallback is closer to useRef, rather than a way to memoize a calculation result.

Looking into the docs I do agree it looks confusing there.

useCallback will return a memoized version of the callback that only changes if one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).

Example

Suppose we have a PureComponent-based child <Pure /> that would re-render only once its props are changed.

This code re-renders the child each time the parent is re-rendered — because the inline function is referentially different each time:

function Parent({ ... }) {
  const [a, setA] = useState(0);
  ... 
  return (
    ...
    <Pure onChange={() => { doSomething(a); }} />
  );
}

We can handle that with the help of useCallback:

function Parent({ ... }) {
  const [a, setA] = useState(0);
  const onPureChange = useCallback(() => {doSomething(a);}, []);
  ... 
  return (
    ...
    <Pure onChange={onPureChange} />
  );
}

But once a is changed we find that the onPureChange handler function we created — and React remembered for us — still points to the old a value! We've got a bug instead of a performance issue! This is because onPureChange uses a closure to access the a variable, which was captured when onPureChange was declared. To fix this we need to let React know where to drop onPureChange and re-create/remember (memoize) a new version that points to the correct data. We do so by adding a as a dependency in the second argument to `useCallback :

const [a, setA] = useState(0);
const onPureChange = useCallback(() => {doSomething(a);}, [a]);

ここで、aが変更されると、React は を再レンダリングします<Parent>。そして、再レンダリング中に、 の依存関係onPureChangeが異なることがわかり、コールバックの新しいバージョンを再作成/記憶する必要があります。これが に渡され<Pure>、参照が異なるため、<Pure>も再レンダリングされます。これですべてが機能します。

PureComponent注: /に限らずReact.memo、 内で依存関係として何かを使用する場合、参照の等価性は重要になることがありますuseEffect

おすすめ記事