0

I've created a sandbox using useMemo to optimize a mock expensive function follow Kent C Dodds example from this post. Memoisation doesn't seem to be working. Any ideas why?

https://codesandbox.io/s/usememo-rfphn?file=/src/index.tsx

Brad Woods
  • 1,507
  • 2
  • 12
  • 30
  • 1
    In the example , useMemo is redundant – gu mingfeng Aug 11 '21 at 08:53
  • Could you elaborate? – Brad Woods Aug 11 '21 at 09:00
  • You can think that Memoisation of useMemo has only one item, useMemo's function will be called when dependency has any change. In your example, child will render when duration changed, but when duration changed useMemo will also be recalled. Remove the useMemo's dependency, you can see useMemo works. – gu mingfeng Aug 11 '21 at 09:06

1 Answers1

2

useMemo() is actually working correctly in your code

You have:

const value = useMemo(() => wait(duration), [duration]);

useMemo() recalculate its value every time any of the values from its dependency changes, and you have [duration] inside your dependency array which change every time, you click the setDuration() button.


If you want to see useMemo() works, make the component re-render without changing its dependency.

Something like this: useMemo()

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
  • Thanks for the example. That makes sense. In the article, it states: "On top of that React also stores previous values given the inputs and will return the previous value given the same previous inputs. That's memoization at work.". Am I incorrect in understanding that as "If you pass in the same value(s) as previous values to useMemo, it will return the previously calculated result". – Brad Woods Aug 11 '21 at 09:22
  • 1
    You are correct, If the next dependency value(s) are `same` as the previous ones, the callback inside useMemo() won't run. `Same` here meaning that they have the same reference (===). – Ryan Le Aug 11 '21 at 09:26
  • I see what you mean. I was assuming it remembered all previous values. But it looks like it only remembers the most recent previous value. – Brad Woods Aug 11 '21 at 09:31
  • Yeah, So the key is `one` not `all` even though it sounds heavy in terms of memory. Great finds, btw – Ryan Le Aug 11 '21 at 09:33