useMemo

Ammar Halees | April 9, 2022

useMemo allows you to cache a computed value between renders, unless it needs to be re-computed.

Syntax

const cachedValue = useMemo(calculatingFn, [dep1, dep2]);

calculatingFn

Typically used for heavy computations.

Input:

  • Takes no parameters.

Output:

  • Returns a value that you want to cache.

Constraints:

  • Must not take any arguments.
  • Must return a value.
  • Must be pure (no side effects, deterministic).

Dependencies

An array of values.
If any of them change, calculatingFn will be invoked again.

Use Cases

  • When you're passing a complex value as props.
  • When you're performing a heavy computation that doesn't need to run every time.

Mental Model

Think of useMemo as a cache.
And the dependency array? That’s the cache invalidator.

Flow

useCallback?

It’s basically useMemo, but designed for functions.

The first parameter is the function you want to cache.

You can think of it as syntactic sugar over useMemo.

FYI

  • React checks if a dependency has changed by comparing the current and previous values using Object.is.

    That’s why dependencies should ideally be primitive or stable values.