Understand the useMemo hook

Introduction - What is memoization in React

Memorization, in a general context, is an optimization technique to improve program speed. Using this technique, we store the results of the function we're optimizing in the browser cache.

If we execute the function without memorization, each time the function is called, it will be re-executed. However, by memorizing the function, when we need to execute it again, if the inputs are the same as the last time, we'll get the results. The function will only be re-executed with new inputs. This way, we avoid unnecessary re-renderings and optimize the process.

What is useMemo and how it works?

In React, useMemo is a hook that performs dynamic memoization. You just need to specify the function needed to store the result and the dependencies that determine whether the function needs to be re-executed.

See the syntax below to understand the useMemo parameters:

useMemo(fn, [dependencies])

const memoizedValue = useMemo(() = > { 
    hardFunction() // Here is a hard function you don't want to recalculate
}, [dependency1, dependency2])

Simple example of use

Lets see an example:

When use useMemo

It's important to consider which scenarios to use useMemo in. Here are some examples:

  • UseMemo is recommended when you have a complex calculation, such as loops involving a list of thousands of items, that depends on data that rarely changes, in a component with multiple renders.

  • Do not use useMemo for simple calculations, such as a simple sum (2+2). This will use up memory space and may affect performance.

Diference between useMemo and React.memo

useMemo, as already described, memorizes the function's result and only reruns it if its dependencies change.

But React.memo is completely different. It can memorize a component, rerendering it only if its properties change. See the example below.

const Child = React.memo(( {value} ) => {
    console.log('Child rendered');
    return <div>{value}</div>
});

In this case, Child will be re-rendered if the value changes.

If the parents are rendered but the value property doesn't change, Child will not be re-rendered.

Good Pratices

1 - Use useMemo only for complex calculations

2 - Be careful with dependencies: always include all inputs used in the function in the dependency list.

0
Subscribe to my newsletter

Read articles from Jonatas Artagnan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jonatas Artagnan
Jonatas Artagnan