DEV Community

Cover image for Understanding the useMemo() hook
Yahaya Oyinkansola
Yahaya Oyinkansola

Posted on

Understanding the useMemo() hook

Hey there, and welcome to another article in my React hook series, you can check articles I have written on the useRef() and useCallback() hooks. Today, I want to share what I have learnt about the useMemo() hook, which almost works the same way with the useCallback() hook.

What is the useMemo() hook?

The useMemo() hook is one of the built-in React hooks used for optimizing the performance of a React application, and it does this by caching the result of an expensive computation (Also known as Memoization). When a component renders, there might be functions that execute some piece of code to calculate data which will be used within that component, not all computations in your React application are expensive, as some are calculated fast as the component renders or re-renders.

Expensive computations can occur if you are fetching data from an API. Let's say for example you are fetching data about all the countries in the world from an API, it makes no sense that each time your component re-renders, you keep fetching all the countries again!, this can definitely slow down the application. In this type of scenario, you can use the useMemo() hook to store the result of that API call so that as the component re-renders, you still have all the countries and the API call only runs if specific data within the application changes, that's the advantage the useMemo() hook gives us!.

If you are familiar with the useCallback() hook, you might think useMemo() does the same thing with useCallback(), but it is important to note that useCallback() stores the entire function declaration, while useMemo() on the other hand stores the result of the function execution, but they both implement memoization.

Now let's look at the syntax of the useMemo() hook

const cachedValue = useMemo(calculateValue, dependencies);
Enter fullscreen mode Exit fullscreen mode
  • calculateValue signifies the function that will be executed, with the result cached.

  • dependencies tells useMemo() what data to monitor so that whenever any change is made, it re-runs the function and caches the new result

I am currently working on implementing this hook in one of my React applications to further show how it works, but to illustrate an example in this article, let's consider a scenario where you have a list of posts that need to be sorted based on a specific criteria. If sorting is an expensive operation and the list of posts doesn't change frequently, you can use useMemo() to optimize that operation.

import { useMemo } from "react";

function Blog({ posts }) {
  const sortedPosts = useMemo(() => {
    console.log("Sorting posts...");
    return posts.sort((a, b) => a.date - b.date);
  }, [posts]);

  return (
    <div>
      {sortedPosts.map((post) => (
        <div key={post.id}>{post.title}</div>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useMemo() is used here to memoize the result of the sorting operation. The sorting function will only be executed when the posts array changes (In cases where an item is removed from the array or added to the array), preventing unnecessary re-sorting on each render.

Conclusion

Even though useMemo() is very helpful with optimizing your application by preventing functions that don't need to always run, it's important to use it only when it's necessary, else your application will become slower rather than faster. Overusing useMemo() can lead to unnecessary memory consumption because React stores the memoized values in memory. It's best to use useMemo() when you have identified performance bottlenecks in a specific component in your application through Profiling.

Top comments (0)