What is useMemo Hook in React?

This article provides a comprehensive overview of the useMemo hook in React, explaining its core purpose of performance optimization through memoization. Readers will learn how useMemo works, its syntax, practical use cases for caching expensive calculations, and the common mistakes to avoid when implementing it in React applications.

Understanding useMemo

The useMemo hook is a built-in React hook that caches the result of a calculation between re-renders. It is used to optimize performance by avoiding expensive calculations on every render when the inputs to those calculations have not changed.

This process of caching a computed result based on its inputs is known as memoization.

How useMemo Works

By default, React re-renders every component inside a tree when state or props change. If your component contains a function that performs a complex, CPU-intensive calculation, React will re-run that calculation on every single render, even if the inputs to the calculation are exactly the same.

useMemo solves this by storing the output of the calculation. On subsequent renders, React will compare the dependency values. If the dependencies have not changed, React skips running the function and returns the cached result.

The Syntax

The useMemo hook accepts two arguments: 1. A calculate function that returns the value you want to cache. 2. A dependency array containing all values used inside the calculation.

import { useMemo } from 'react';

const memoizedValue = useMemo(() => {
  return computeExpensiveValue(a, b);
}, [a, b]);

When to Use useMemo

You should not wrap every calculation in useMemo. The hook itself has a small performance overhead. Use useMemo in the following scenarios:

1. Filtering or Transforming Large Datasets

If you have a large array of data and you need to filter, sort, or map through it, useMemo prevents these operations from running unless the data or the filter criteria change.

const visibleTodos = useMemo(() => {
  return todos.filter(todo => todo.completed === filterStatus);
}, [todos, filterStatus]);

2. Preventing Unnecessary Child Re-renders

If you pass a computed object or array as a prop to a child component, React will treat it as a new reference on every render, causing the child component to re-render. Memoizing the object ensures the reference remains the same unless dependencies change.

When to Avoid useMemo