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:
- When the user types into the input field, the
setFilterTextfunction updates thefilterTextstate. - The state update forces the
ProductListcomponent to re-render. - During the re-render, React checks the dependency array
[products, filterText]. - Because
filterTexthas changed, React executes the filtering function again, updatingfilteredProductswith the new filtered list.
Common Mistakes to Avoid
- Leaving the Dependency Array Empty: If you pass an
empty array
[], the memoized value will only be calculated once during the initial mount and will never update, even if the variables used inside the function change. - Omitting the Dependency Array: If you omit the
dependency array entirely,
useMemowill run on every single render, defeating the purpose of memoization. - Missing Dependencies: Ensure that every state,
prop, or context variable referenced inside the
useMemocallback function is included in the dependency array. Failing to do so can result in “stale” data becauseuseMemowill not update when those unlisted variables change.