How to Update useMemo Hook in React

In React, the useMemo hook is used to cache the result of a calculation between re-renders to improve performance. To update a useMemo hook, you must update one or more of the dependencies declared in its dependency array. This article explains how the dependency array triggers a recalculation, provides a practical code example, and outlines best practices to ensure your memoized values update correctly.

The Dependency Array: The Key to Updating useMemo

The useMemo hook accepts two arguments: a calculate function that returns a value, and an array of dependencies. React will only recalculate the memoized value when one of the dependencies in the array changes.

The basic syntax looks like this:

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

In this example, memoizedValue will only be updated if either variable a or b changes between renders. If the component re-renders but a and b remain the same, React skips the function execution and returns the cached value.

Step-by-Step Example of Updating useMemo

To trigger an update, you must link the dependencies of useMemo to state variables or props that change over time.

Here is a practical example of a component that filters a list of items based on a search query:

import React, { useState, useMemo } from 'react';

function ProductList({ products }) {
  const [filterText, setFilterText] = useState('');

  // useMemo updates only when 'products' or 'filterText' changes
  const filteredProducts = useMemo(() => {
    return products.filter(product => 
      product.name.toLowerCase().includes(filterText.toLowerCase())
    );
  }, [products, filterText]); 

  return (
    <div>
      <input 
        type="text" 
        value={filterText} 
        onChange={(e) => setFilterText(e.target.value)} 
        placeholder="Search products..."
      />
      <ul>
        {filteredProducts.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}

How the Update Works in This Example:

  1. When the user types into the input field, the setFilterText function updates the filterText state.
  2. The state update forces the ProductList component to re-render.
  3. During the re-render, React checks the dependency array [products, filterText].
  4. Because filterText has changed, React executes the filtering function again, updating filteredProducts with the new filtered list.

Common Mistakes to Avoid