Harry Yates
I'm a web developer focused on TypeScript, React, and Three.js.
useMemo
is a hook that optimises the performance of React applications by the art of memoisation.
This means it caches a computed value and only re-computes it when one of its dependencies changes.
Understanding when and how to use useMemo
can enhance efficiency.
Memoisation is a technique that is similar to having a well-organised ledger.
In React's world, useMemo
serves as a meticulous accountant, ensuring costly computed values are not recalculated with every render— unless their dependencies evolve.
useMemo
with a function that computes a value—a sort of directive.useMemo
they will only re-invocate the function if these dependencies have shifted since the last soirée.useMemo
should be used judiciously, as unnecessary use can lead to code complexity and even degrade performance due to the overhead of maintaining the memoisation cache. Here are ideal scenarios for using useMemo
:
Consider a scenario where you have an array of items, and you need to perform an expensive operation like filtering and sorting based on user input:
In this example, useMemo
is used to ensure that the filtering and sorting operation is only executed when items
or filter
changes, not on every render.
useMemo
when there is a clear performance benefit. Using it indiscriminately can lead to more complex and less maintainable code.