React Foundations · Performance

Memoising a value

useMemo

Memoising a value with useMemo

Some calculations are slow. If you recompute a long list on every render, the work adds up — even when nothing it depends on has changed.

useMemo caches a calculation. React runs it on the first render and keeps the result. On later renders it hands back the stored value, and recomputes only when a dependency changes:

const doubled = useMemo(() => value * 2, [value]);

Here React recomputes doubled only when value changes.

Since the React Compiler (stable since v1.0, and on by default in the templates you start from), components are memoised for you. The compiler reads your code and inserts the same caching. That changes the advice: useMemo is no longer something to sprinkle everywhere. Treat it as an escape hatch for the few places where you want to be explicit — a value you put in an Effect's dependency array, or one you know is genuinely expensive:

const sorted = useMemo(() => [...items].sort(), [items]);

useMemo is a performance tool, not a correctness one: the component renders the same output with or without it. Reach for it deliberately, not by default.

Your job is to memoise a derived value.

Challenge

A doubling is recomputed on every render, even when the value has not moved. Export an App component from App.jsx that takes a value prop and renders its double in a paragraph, computed with useMemo.

The Test renders <App value={21} /> and expects the paragraph to read 42. Make the memo depend on value, and render the memoised result. The starter renders the value unchanged, so the Test fails.

App.jsx
export function App({ value }) {
  return <p>{value}</p>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.