Skip to main content
useMemo returns a memoized value. It only recomputes the value when one of the dependencies has changed, helping to avoid expensive calculations on every render.

Signature

Parameters

() => T
required
A function that computes and returns the value to be memoized. This function should be pure and take no arguments.
ReadonlyArray<unknown> | undefined
required
An array of dependencies. The memoized value will only be recomputed when one of these values changes (compared using ===). If undefined is passed, a new value will be computed whenever a new function instance is passed as the first argument.

Returns

Returns the memoized value of type T. On the initial render, it returns the result of calling factory(). On subsequent renders, it returns the cached value if dependencies haven’t changed, or recomputes by calling factory() if they have.

Basic Usage

Expensive Calculations

Memoizing Objects

Sorting and Filtering

Computing Derived State

Referential Equality

Creating Regex Patterns

Graph Computations

With undefined Dependencies

useMemo is an optimization tool. Your code should work correctly without it, then add it to improve performance where needed.
Don’t use useMemo for everything. It has overhead, so only use it for computationally expensive operations or when maintaining referential equality is important for child component optimization.
Unlike React, Preact requires the inputs parameter. Pass undefined explicitly if you want to recompute whenever the factory function changes.