Harry Yates

I'm a web developer focused on TypeScript, React, and Three.js.

useMemo

Thu, 11th Apr 2024

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.

check and repeat

What is Memoisation?

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.

How Does useMemo Work?

  • Function: Present useMemo with a function that computes a value—a sort of directive.
  • Dependency Array: Accompany this with an array of dependencies. Like a loyal butler, useMemo they will only re-invocate the function if these dependencies have shifted since the last soirée.

When to Use useMemo

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:

  • Complex Calculations: Invoked when your component engages in computations so costly they could bankrupt lesser technologies.
  • Referential Equality: Employed to ensure that the reference between renders remains as unbroken as a gentleman’s word, crucial for nested objects and arrays.

Example Usage of 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:

useMemo example

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.

Best Practices and Pitfalls

  • Do Not Overuse: Only use useMemo when there is a clear performance benefit. Using it indiscriminately can lead to more complex and less maintainable code.
  • Correct Dependency Array: Ensure all variables affecting the computed value are included in the dependency array to avoid bugs due to stale closures.