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.
Slow computation each time && counter increments each time, despite same input.
Again, here is the link to the project. Where is my mistake?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With