207

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>

3
  • 5
    I don't think you need to call computedCallback = calcCallback();. computedCallback should just be = calcCallback, it will update the callback once neverChange` changes.
    – Noitidart
    Commented Mar 3, 2019 at 2:17
  • 1
    useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
    – Henry Liu
    Commented Feb 6, 2020 at 15:36
  • Whenever you declare a function with the parenthesis it will invocate the function. As a result, whenever second is updated it will execute the calcCallback func Commented Mar 30, 2021 at 4:02

8 Answers 8

358

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]);

Now, if a is changed, React re-renders the <Parent>. And during re-render, it sees that the dependency for onPureChange is different, and there is a need to re-create/memoize a new version of the callback. This is passed to <Pure> and since it's referentially different, <Pure> is re-rendered too. Finally everything works!

NB not just for PureComponent/React.memo, referential equality may be critical when use something as a dependency in useEffect.

6
  • 2
    I don't think this comment tied everything together very well. Does adding the callback and dependency array mean that <Pure /> will not be rerendered if a has not changed?
    – maxflow
    Commented Feb 27, 2021 at 10:00
  • 1
    since onPureChange callback will be referentially the same in that case, then yes, <Pure> will not rerender when its parent rerenders
    – skyboyer
    Commented Feb 27, 2021 at 11:14
  • 1
    And <Pure> will re-render if anything in its dependency array (a in this case) changes, right? But when I look at that sentence, it gives me the reverse perspective "Now, if a is changed, React re-renders the component. And during re-render..." Commented Jun 3, 2022 at 9:54
  • @AhmetFiratKeler yes, once a is changed in Parent it re-renders Parent. And during re-render it goes to re-render Pure. If it's only prop onChange stays referentially the same(which is impossible when declaring inline but is possible with useCallback) Pure will not be re-rendered.
    – skyboyer
    Commented Jun 3, 2022 at 10:40
  • 1
    Okay, as I understand. But your paragraph I mentioned earlier does need an edit for my opinion. Commented Jun 3, 2022 at 11:18
134

useMemo and useCallback use memoization.

I like to think of memoization as remembering something.

While both useMemo and useCallback remember something between renders until the dependancies change, the difference is just what they remember.

useMemo will remember the returned value from your function.

useCallback will remember your actual function.

Source: What is the difference between useMemo and useCallback?

2
  • 2
    By default a function, which is defined within a component, is re-defined at every render, so useCallback prevents this render triggered re-definition and subsequent re-execution. Is that correct?
    – jbuddy_13
    Commented Mar 16, 2022 at 18:52
  • @jbuddy_13 yeah, that's it regards useCallback and useMemo remembers the return value, if it's the same, it won't re-render. Commented May 4, 2022 at 4:02
99

One-liner for useCallback vs useMemo:

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).


With useCallback you memoize functions, useMemo memoizes any computed value:

const fn = () => 42 // assuming expensive calculation here
const memoFn = useCallback(fn, [dep]) // (1)
const memoFnReturn = useMemo(fn, [dep]) // (2)

(1) will return a memoized version of fn - same reference across multiple renders, as long as dep is the same. But every time you invoke memoFn, that complex computation starts again.

(2) will invoke fn every time dep changes and remember its returned value (42 here), which is then stored in memoFnReturn.

const App = () => {
  const [dep, setDep] = useState(0);
  const fn = () => 42 + dep; // assuming expensive calculation here
  const memoFn = useCallback(fn, [dep]); // (1)
  const memoFnReturn = useMemo(fn, [dep]); // (2)

  return (
    <div>
      <p> memoFn is {typeof memoFn} </p>
      <p>
        Every call starts new calculation, e.g. {memoFn()} {memoFn()}
      </p>
      <p>memoFnReturn is {memoFnReturn}</p>
      <p>
        Only one calculation for same dep, e.g. {memoFnReturn} {memoFnReturn}
      </p>
      <button onClick={() => setDep((p) => p + 1)}>Change dep</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<div id="root"></div>
<script>var { useReducer, useEffect, useState, useRef, useCallback, useMemo } = React</script>

2
  • 2
    This one liner has hit so hard. Thank you :) Commented Feb 26, 2022 at 11:26
  • How does "same reference across multiple renders" change anything? Commented Jun 13 at 16:07
24

You are calling the memoized callback every time, when you do:

const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
const computedCallback = calcCallback();

This is why the count of useCallback is going up. However the function never changes, it never *****creates**** a new callback, its always the same. Meaning useCallback is correctly doing it's job.

Let's making some changes in your code to see this is true. Let's create a global variable, lastComputedCallback, that will keep track of if a new (different) function is returned. If a new function is returned, that means useCallback just "executed again". So when it executes again we will call expensiveCalc('useCallback'), as this is how you are counting if useCallback did work. I do this in the code below, and it is now clear that useCallback is memoizing as expected.

If you want to see useCallback re-create the function everytime, then uncomment the line in the array that passes second. You will see it re-create the function.

'use strict';

const { useState, useCallback, useMemo } = React;

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

let lastComputedCallback;
function App() {
  const [second, setSecond] = useState(0);
  
  // This 👇 is not expensive, and it will execute every render, this is fine, creating a function every render is about as cheap as setting a variable to true every render.
  const computedCallback = useCallback(() => expensiveCalc('useCallback'), [
    neverChange,
    // second // uncomment this to make it return a new callback every second
  ]);
  
  
  if (computedCallback !== lastComputedCallback) {
    lastComputedCallback = computedCallback
    // This 👇 executes everytime computedCallback is changed. Running this callback is expensive, that is true.
    computedCallback();
  }
  // This 👇 executes once
  const computedMemo = useMemo(() => expensiveCalc('useMemo'), [neverChange]);
  
  setTimeout(() => setSecond(second + 1), oneSecond);
  return `
    useCallback: ${expensiveCalcExecutedTimes.useCallback} 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 < 10000) 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>

Benefit of useCallback is that the function returned is the same, so react is not removeEventListener'ing and addEventListenering on the element everytime, UNLESS the computedCallback changes. And the computedCallback only changes when the variables change. Thus react will only addEventListener once.

Great question, I learned a lot by answering it.

3
  • 2
    just small comment to good answer: the main goal not about addEventListener/removeEventListener(this op itself is not heavy since does not lead to DOM reflow/repaint) but to avoid re-rendering PureComponent(or with custom shouldComponentUpdate()) child that uses this callback
    – skyboyer
    Commented Mar 3, 2019 at 9:12
  • Thanks @skyboyer I had no idea about *EventListener being cheap, that's a great point about it not causing reflow/paint! I always thought it was expensive so I tried to avoid it. So in the case I am not passing to a PureComponent, is the complexity added by useCallback worth the trade off of having react and DOM do extra complexity remove/addEventListener?
    – Noitidart
    Commented Mar 3, 2019 at 13:05
  • 1
    if don't use PureComponent or custom shouldComponentUpdate for nested components then useCallback will not add any value(overhead by extra checking for second useCallback argumgent will nullify skipping extra removeEventListener/addEventListener move)
    – skyboyer
    Commented Mar 3, 2019 at 13:29
3

useCallback() and useMemo() are pretty much same but useCallback saves the function reference in the memory and checks on the second render whether it's same or not if it is same then it returns last saved function without recreating it and if it is changed then it returns a new function and replaces it with older function in memory for future rendering. useMemo works in same manner but it can't save your function but the computed or returned value. On every render useMemo checks the value if the returned value of your function is the same on second render then it will return same value without recalculating the function value and if the value is not same on second render then it will call the function and return new value and store it for future render.

NOTE: You have to be careful when you have need to use these hooks. Unnecessary use of these hooks can make your app performance worse because they use memory. Be sure if your component re-renders many times with heavy calculations then it is good to use these hooks.

3

Before knowing in detail about useCallback and useMemo hooks, let’s understand how the React compares the values added in dependency array of useEffect.

React compares these values by using Object.is() i.e., by referential equality. In general, for primitive data types the values are compared based on its value if they are equal then it is considered as similar otherwise they are treated as different and for non primitive data types (objects, arrays or functions) the values are compared based on the memory location reference, if the values shares the same memory location then they are known to be similar otherwise treated as different (Even though the two objects has same properties if the memory location reference is different then they are considered as not same).

Now, if the dependency of the useEffect is dependent on primitive data type values then there is no issue as we have already seen how the React would compare them. The problem is with non primitive data type values as we have already got to know that for the same two objects the memory location reference to be same in order for them to be considered as similar.

Now the question arises, how can we make the two same non primitive data values to be considered as similar. Yes, the only possible answer is to make them share the same memory location reference, now how do we actually do this?? Here comes useCallback and useMemo hooks which helps in storing the non primitive data type values under the same memory reference if there is no change in the values between the rendering.

Now, the useEffect can compare its non primitive dependencies and be made to run only if there is actual change in the dependencies.

If the function is used as dependency in the useEffect then, that function can be wrapped in the useCallback which returns memoized function i.e., returns same function definition stored under the same memory reference unless function dependency is not changed.

    const memoizedFunc = useCallback(function useEffectDependentFunction(){ 
     return someValue; 
    }, [useEffectDependentFunction_dependency]) 
     
    // useEffectDependentFunction will be stored in the same memory location under the name memoizedFunc untill useEffectDependentFunction_dependency is not changed.

 
 
useEffect(()=>{ 
//do something 
}, [memoizedFunc]} 

If some array or object or value obtained after some calculation from a function is to be used as dependency in the useEffect then, that function which involves the calculation can be wrapped in useMemo which returns memoized array or object or value depending on what the use case is, unlike useCallback it wont return the function itself instead it returns the calculated value from the function.

const memoizedValue = useMemo(()=>function useEffectDependentValueYieldingFunction(){ 
//some calculation 
 return someValue; 
}, [useEffectDependentValueYieldingFunction_dependency]) 
 
// the value returned from the useEffectDependentValueYieldingFunction will be stored in the same memory location under the name memoizedValue untill useEffectDependentValueYieldingFunction_dependency is not changed. 
 
useEffect(()=>{ 
//do something 
}, [memoizedValue]} 

That’s it.

The above explained scenario is one of the use cases where useCallback and useMemo are used efficiently.

2

In both useMemo and useCallback, the hook accepts a function and an array of dependencies. The key different is:

  • useMemo will memory the returned value, it caches a value type.

Usecase: Using it for caching calculation value heavily.

  • useCallback will memory the function, it caches a function.

Usecase: Using it for caching API calling method which is only call by action of user.

Cheer!

0

I think its also worth noting that there may be some other optimisations going on - for example useMemo might be storing the call history of every function execution in memory whereas useCallback probably would not have any need to do that.

The reason I say that is because there would be no purpose to storing a history of callbacks in memory as the callback will execute regardless but also because the purpose is to keep referential equality to prevent re-renders of children that use the function as props, so if the referenced changed (even to a previous reference) the function would re-render anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.