useMemo hook
Maya Ifrim

Maya Ifrim

Apr 10, 2023

useMemo hook

useMemo() is a React Hook that allows you to memoize or cache the results of a function so that it only re-runs when its dependencies change so basically lets you cache the result of a calculation between re-renders. This can be useful when you have a computationally expensive function that gets called frequently, but whose output doesn't change often.

You need to pass the following to useMemo:

a) a calculation function that takes no arguments, like () =>, and simply returns the result of the calculation;

b) a list of dependencies including every value within your component that’s used inside your calculation.

memo-modified (1).png

Be aware, that useMemo() can be called only at the top level of the component. You can’t call it inside loops or conditions.

On the initial render, the value you’ll get from useMemo() will be the output of your calculation function.

On subsequent re-renders, React will check the dependencies passed to useMemo() during the last render.

If none of these dependencies have changed, useMemo() will return the previously cached value without re-running the calculation function. However, if any of the dependencies have changed, useMemo() will re-run the calculation function and return a new value. Essentially, useMemo() caches the calculation result between renders and only recomputes the result when the dependencies change.

For a better understanding lets see the two examples below.

In the first example,  useMemo is used to memoize the result of converting a user input text to uppercase. The calculation is performed when the user types in the input field and changes the "text" state. This means that the expensive calculation will be re-executed every time the "text" variable changes, but not on every re-render of the component.


In the second example, the dependencies array is left empty [] because the calculation doesn't depend on any external variables.

download (2).png

The calculation itself is just a simple loop that adds up a billion numbers.

Now, if you open your console and run the code, you'll notice that the expensive calculation only runs once, when the component is first mounted. After that, it's memoized and the same result is returned on subsequent renders, even when you click the "Increment Count" button.

Maya Ifrim

Maya Ifrim

Passionate React developer with a love for crafting beautiful and user-friendly interfaces.

Leave a comment

Related Posts