liveBook · Manning

useMemo

As explained in React Quickly, Second Edition

useMemo is a React Hook that memoizes a calculated value and reuses it across renders until its dependencies change.

useMemo memoizes a calculated value in a functional component, reusing it across renders until its dependencies change. It can help avoid expensive recalculations when the inputs stay the same. section 7.3.1 section 7.0

A costly calculation

If an input contains a password and displaying its cryptographic hash is expensive, useMemo can avoid recalculating the hash when the password has not changed. section 7.3.1

Listing 4.17 Gallery v4 using functions (excerpt)
import { useMemo } from 'react';                      #1
...
function Image({ index, title }) {
  const id = useMemo(() =>                            #2
    `image-${Math.floor(Math.random() * 1000000)}`,   #2
  []);                                                #2
  return (
    <figure style={{ margin: "5px" }} id={id}>
      <img src={`//picsum.photos/id/${index}/150/150/`} alt={title} />
      <figcaption>
        <h3>Species: {title}</h3>
      </figcaption>
    </figure>
  );
}
...

A gallery image uses useMemo with an empty dependency array to generate an ID once and reuse it across renders. section 4.4.4

How React Quickly, Second Edition covers it

How deep it goes
Explains dependency-triggered recalculation and illustrates an empty dependency array with a generated ID.
Examples
Uses an expensive password hash and a gallery image's generated ID to demonstrate memoized values.
What you can do after
Apply useMemo to reuse a generated ID across renders or recalculate a value only when dependencies change.
How it connects
Connects useMemo to memoization hooks and contrasts it with useCallback, which memoizes functions.

Also explained in

Compare how 3 books explain useMemo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.