liveBook · Manning

useMemo

As explained in React Hooks in Action: With Suspense and Concurrent Mode

useMemo is a React Hook that memoizes a calculated value and recomputes it when specified dependencies change.

useMemo memoizes a calculated value so React can avoid repeating an expensive computation when its dependencies have not changed. It fits performance-sensitive UI work where unchanged output would otherwise slow rendering and degrade user experience. section 7.0 section 7.2

Call useMemo with a calculation function and a dependency array:

  • Include every value used by the calculation in the dependency array. section 7.2
  • When dependencies match the previous values in the same order, React may return the stored result. section 7.2
  • When a dependency changes, React recalculates and stores the new result. section 7.2
  • Treat memoization as an optimization, not a guarantee: React may discard its stored value to free memory. section 7.2 section 7.5
  • Omitting dependencies reruns the calculation every time; an empty array permits reuse because its values never change, but still does not guarantee reuse. section 7.2

Memoizing a bookings grid

BookingsGrid generates grid, session, and date data from the selected bookable and week. Wrapping getGrid in useMemo regenerates that data only when bookable or week.start changes: const {grid, sessions, dates} = useMemo(() => bookable ? getGrid(bookable, week.start) : {}, [bookable, week.start]); The component still uses useState for bookings and errors and useEffect for fetching data. section 7.4.4

Figure 7.3 Call the useMemo hook with a function and a list of dependencies.

A figure visualizes the useMemo call with its calculation function and dependency list. section 7.2

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains calculation functions, dependency comparison, cache caveats, and a bookings-grid implementation, while stopping short of React internals.
Examples
Demonstrates expensive anagram generation and memoized booking-grid generation based on a selected bookable and week.
What it assumes
Assumes familiarity with React Hooks and JavaScript functions, while teaching memoization and dependency-array behavior directly.
What you can do after
Apply useMemo to wrap an expensive calculation and regenerate it when named dependencies change.
How it connects
Connects useMemo with dependency arrays, expensive computations, rendering, useState, and useEffect.

Also explained in

Compare how 4 books explain useMemo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.