Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useMemo hook use case

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?

like image 345
Thierry Prost Avatar asked Oct 15 '22 12:10

Thierry Prost


1 Answers

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.

like image 83
Domino987 Avatar answered Nov 15 '22 04:11

Domino987