5

Context

After reading through the official doc for hooks, I wanted to try useMemo in one of my projects.

To test it, I set up a sandbox project here.

The example uses an expensive computation at every input change (see "ellapsed ms"). Every time this expensive computation runs, a counter gets incremented (see "counter").

Example is perfect for memoization so I use useMemo hook, but the results were not what I expected, leading me to believe I have misunderstood something fundamentally here.


Expected:

  • first render slow: computation && counter incrementation of a value
  • Rerenders near instant computation with no counter incrementation

Actual:

Slow computation each time && counter increments each time, despite same input.

useMemo_example

Again, here is the link to the project. Where is my mistake?

1 Answer 1

3

useMemo gets triggered every time the value changes because you add it with [value] as the second parameter. That is why inserting a new value into the input leads to a new computation. useMemo is used to prevent unnecessary calculations, if something else, but not value, changes. But since the only thing that can change is your value, you see the calculation done every time. If the component has more state/prop values, you would see that the computation will be skipped, if these other state/prop values change. Hope this makes it clearer. Happy coding.

Sign up to request clarification or add additional context in comments.

2 Comments

So to be clear, it doesn't use memoization based on the [value], but to the contrary it ignores all changes except those on [value]. Now that you explained it, it's just like useEffect's deps variable. Makes sense
Yes exactly, on every render, it will check if value changed. If it did, the computation will be triggered. If not, it will return the previous calculated value,

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.