How to useMemo in React


useMemo Hook can help us improve performance in our React application.

This hook allows you to apply memoization to any value type (not just functions) so that we can avoid calling them every time we render

useMemo has 2 arguments:

  • The first argument is a function that does the complex calculation we want to memoize
  • The second arguments is a dependency array for that memoization.
const memoizedValue = React.useMemo(() => computeExpensiveValue(a, b), [a, b]);

React’s useMemo Hook is different from React.memo. While useMemo is used to memoize values, React.memo is used to wrap React components to prevent re-renderings.

When to use useMemo

Before implementing useMemo, we should check if we have expensive performance issues, which are functions using up a lot of resources (memory).

Please note that if we use useMemo too often in an application, it can harm the performance.

The useCallback hook is similar to useMemo, but it returns a memoized function, while useMemo has a function that returns a value.