When and How to Use useMemo in React

Written by funkymonkey | Published 2023/05/30
Tech Story Tags: react | front-end-development | blogging-fellowship | usememo | usememo-usecallback-difference | memoization | website-optimization | hackernoon-es | hackernoon-hi | hackernoon-zh | hackernoon-vi | hackernoon-fr | hackernoon-pt | hackernoon-ja

TLDRuseMemo is a built in hook that can help with performance with your web app through memoization.via the TL;DR App

While doing work in frontend development, you may have come across useMemo. For those unfamiliar with it, we will explain how to use useMemo in React and also the most important/prominent use cases.

What is useMemo?

useMemo is a great built-in hook that can help with the performance of your web app. We know that in react, components are rendered whenever there is a change in the component’s state or props.
Components that are re-rendered will also recompute functions that are being used within. 
Therefore, if there are heavy, expensive functions, performance can be affected as they must be computed every time. useMemo helps memoize these functions in order to optimize performance.

How Does useMemo Work in React? 

In order to understand useMemo, we need to reflect back on what memoization is.
If there is a function that is expensive, such as fetching a lot of data, memoization is a way to store the result of that function so that it does not have to be called over and over again.
useMemo will take the function that it is wrapping, and cache the results of that function so that it can be provided to you when necessary without doing the computations all over again. 

How Do You Use useMemo in React?

As a built-in hook, you can import the hook from React and use it at the top level.
Then, you may wrap your expensive computation with useMemo by declaring some constant or variable and assigning it to the result of your hook. 
Don’t forget to add your dependencies as this is how useMemo determines whether it must recompute the function again.
If your dependency changes, then useMemo will know to recompute the value so that it is caching the right result at all times. 
import { useMemo } from 'react';


function someExpensiveFunction(n) {
   return n * n;
}


function myFunction({n}) {
   const result = useMemo(() => someExpensiveFunction(n), [n]);
   return (
       <div>{result}</div>
   );
}
For example, if you passed in the value 5 to
n
, it would cache the value of 25. If
n
changed values to 7, useMemo knows that it is a dependency and will recompute to the value of 49 and cache that result instead. 
This is especially useful when your frontend application is making requests to an API. 
These requests can get expensive, especially if you are fetching large amounts of data.
Perhaps your application has some components that need this data, but you don’t want to do an API call every time the component is rendered.
Then, caching your results with useMemo may be your best bet. 
import React, { useMemo } from 'react';
import axios from 'axios';


const ApiComponent = () => {
   const memoizedResults = useMemo(async () => {
       try {
           const apiResponse = await axios.get('http://apicall.com/somedata');
           return apiResponse.data;
       } catch (error) {
           return error;
       }
   }, []);


   return (
       <div>{apiResponse}</div>
   )
}
As you can see, our dependency is empty because we only want it to render once, since the value won’t actually change. We just want to make the API call once, when it first renders.
Then, this value will be reused in subsequent renders. 

When Is Using useMemo a Bad Idea?

As useful as the hook is, using useMemo constantly is not necessarily a good idea. It may be tempting to wrap every function you write with useMemo in order to ‘save’ calculations.
However, using it when it is not needed can actually slow down your application instead. 
1. Trivial computations
If the function you are wrapping with useMemo is a simple computation, then the cost of using useMemo can be more consequential.
If you are able to determine that the weight of your function is quite small, for example, O(n) time, then it is appropriate to determine that the hook is not needed. 
2. When your function may affect external states and variables
If your function involves making modifications to other global variables, or depends on them, then using useMemo may not be a good idea.
As described before, useMemo only recomputes the function when a dependency changes.
However, if the function makes use of variables or calls that are not necessarily a dependency change, then it will not recompute the value, causing the cached result to be incorrect. 

What is the Difference Between useMemo and useCallback? 

Some of you may also be familiar with useCallback, which serves a similar purpose to useMemo. This article will not dive deeply into useCallback, but we will differentiate when to use the two functions. 
It can be easy to confuse useMemo and useCallback, because they are both hooks that work to optimize your application by memoizing something for you. However, it is important to note that the thing that they are memoizing is different. 
In most cases, useMemo memoizes values while useCallback memoizes functions. As seen in the name, useCallback is used to memoize callback functions, especially those that are passed down to children components as props. Callback functions can depend on certain values or references which can change overtime, which means that updates to these functions will cause a re-render in components that use them. Therefore, memoizing them can help prevent re-renders, which can cost us optimization. 
However, as useMemo can memoize both functions and values, it can be used in place of useCallback hooks. Still, it is important to consider the context of your situation and use hooks appropriately to use them as intended. 

Final Thoughts

useMemo overall…is a great, flexible hook that can memoize values for you and avoid re-renders. By using the hook strategically, you can optimize your application, reducing computations, and allowing the user to have a faster and smoother experience. 
Let useMemo give your users a… memorable experience!

Written by funkymonkey | A fiend for pickles and chocolate milk. But not together.
Published by HackerNoon on 2023/05/30