Render optimization in React app: Memoization using useMemo


What is the useMemo hook?

The useMemo hook is one of the additional hooks that are implemented in React. The purpose of the useMemo hook is to memoize the return value of a function i.e it executes some function & remembers the value of that function.

Syntax: – const memoVal= useMemo(funcThatReturnsValue,arrayDependencies)

useMemo hook accepts two arguments i.e., the first argument is the function that returns the value which is to be memoized & the second argument is the dependency array.

The useMemo hook monitors the values passed to the dependency array for any changes.

Once there is a change in the dependency, the function is passed to the useMemo hook as the first argument runs again. In case there occurs no change in the dependency, the useMemo hook returns the memoized value stored in the previous invocation.

When to use the useMemo hook?

useMemo is a suitable hook to use when we have a component that always stays the same & we don’t wish to re-render it every time a state changes, to improve the performance.

useMemo references the concept of memoization (which should not be confused with memorization), which means returning the cached result instead of rendering the component again.

There are 2 main reasons to the use useMemo hook in our React application,

  1. It returns referential equality between renders for values.
  2. Computationally expensive applications.

useMemo hook mainly deals with large data items such as Graphs, Charts, Plotting data & Large Mathematical equations.

  • Below is an example to understand the useMemo hook shortly,

The output of the above example is,

Let’s sum up,

The React useMemo hook can be helpful when you look for ways to improve the performance of the React applications. It can help you optimize expensive computations by the memoizing output of these computations & run them again when necessary.

About the author

Jaid Shaikh
By Jaid Shaikh