DEV Community

Cover image for Additional Hooks in React - useMemo()
Olena Drugalya
Olena Drugalya

Posted on

Additional Hooks in React - useMemo()

This blog post continues the series about React Hooks.

It covers one of additional hooks in React - useMemo().

What is useMemo()?

useMemo() is JavaScript function, which returns a memoized value. What kind of value is that?

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

Function is considered expensive, when it synchronously calculates a value which is computationally expensive to calculate or has a long for loop. Expensive operations can be costly in either time, memory, or processing. In addition to potential technical issues, this may lead to poor user experience.

So, this hooks returns a cached value of an expensive function.

Let's look at this hook more closely below.

How and when use useMemo()

To use this hook, you need to import it first from React library like this:

import {useMemo} from 'react';
Enter fullscreen mode Exit fullscreen mode

You can use this hook without import as well like this - React.useMemo(), for me it's just more convenient to import and destructure first this function and then use it when need in the code.

Afterwards we can set up this hook like this:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Enter fullscreen mode Exit fullscreen mode

Here we create a variable to store the result of useMemo() hook, which is the memoized value.

useMemo() accepts 2 arguments:

1.expensive function (in out example- computeExpensiveValue(a, b))
2.array of dependencies (in our example - [a, b])

The dependencies are the elements useMemo watches: if there are no changes, the function result will stay the same. Otherwise, it will re-run the function. If they don’t change, it doesn’t matter if our entire component re-renders, the function won’t re-run but instead return the stored result. This optimization helps to avoid expensive calculations on every render.
If no array is provided, a new value will be computed on every render.

Conclusion

useMemo is used mainly for performance optimisation. When looking to implement useMemo, you can check with profiling tools to identify expensive performance issues (those which are using up a lot of resources (like memory)). If you are defining a good number of variables in a function at render, it makes sense to memoize with useMemo.

BUT - if you implement useMemo too often in an application, it can harm the performance. The more you use the hook, the more your application has to allocate memory. Use it wisely!

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

Top comments (0)