blenko
blenko

Reputation: 53

Should the React useMemo hook memoize repeat calls with same dependency values?

I have an issue where a (fake) long running / expensive function inside a functional component doesn't appear to be memoized how I would think it would be.

From my understanding of memoization, calling a memoized function with the same param value would simply return the result of the previous call.

That is ONLY happening with useMemo (in my app at least) when values on the component change that are not in the dependencies list. I get that different values would need to rerun the expensive function again, but even if I call the function with a previously used value (value / primitive types, not reference types / objects), it re runs the expensive function again.

Either I've not got something quite right or my understanding of what useMemo does isn't quite right (is this where React.memo comes in?).

This can be seen in this rudimentary stackblitz.

Could anyone tell me where I'm going wrong please.

Upvotes: 5

Views: 4020

Answers (1)

Ashish
Ashish

Reputation: 1121

What are you thinking is you can say 50% correct.

useMemo does not execute the code again for same set of parameters, but

It only remembers last value of parameters.

In your example, when you are clicking + and - button, you are changing value of value from previous value. On 2nd click if you are coming back to same value, it does not mean memoize will return value wothout executing the function.

Try to add a button and on click on it set same current value setValue(value), you will see there is not recalculation happening.

Upvotes: 11

Related Questions