ReactMedium

What is memoization in React?

Memoization is caching the result of work so it is reused when the inputs have not changed. In React it takes three forms: memo caches a component's rendered output for equal props, useMemo caches a computed value, and useCallback caches a function reference. The React Compiler (1.0, 2025) applies memoization automatically at build time.

The tools

ToolCachesRecomputes when
memo(Component)rendered outputprops change (shallow compare)
useMemo(fn, deps)a valuea dependency changes
useCallback(fn, deps)a functiona dependency changes
React.cache(fn) (Server Components)function result per requestarguments differ

Why it matters

  • Avoids expensive recalculations.
  • Keeps references stable so memoized children skip rendering and effects do not re-run.

Costs

  • Memory for the cached values.
  • Comparison of dependencies on every render.
  • Code complexity and the risk of stale values when dependencies are wrong.

React Compiler

It analyzes components and hooks and inserts memoization automatically, including fine-grained caching of individual JSX elements that is impractical by hand. It requires following the Rules of React (pure components, hooks rules); the eslint-plugin-react-hooks compiler rules report code it cannot optimize. With it, write plain code and keep useMemo/useCallback as escape hatches (for example to stabilize an effect dependency deliberately).

Rule of thumb without the compiler

Memoize when a measurement shows slow renders, for large lists, or for values that are dependencies of effects or memoized children.

Code example

tsx
1import { memo, useCallback, useMemo, useState } from "react";
2
3type Point = { x: number; y: number };
4
5// memo: skip re-rendering when props are equal
6const Plot = memo(function Plot({ points, onPick }: { points: Point[]; onPick: (p: Point) => void }) {
7 return <svg width={200} height={100}>{points.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={3} onClick={() => onPick(p)} />)}</svg>;
8});
9
10export function Analytics({ raw }: { raw: number[] }) {
11 const [label, setLabel] = useState("");
12
13 // useMemo: cache an expensive derived value
14 const points = useMemo(() => raw.map((v, i) => ({ x: i * 10, y: 100 - v })), [raw]);
15
16 // useCallback: cache a function so Plot's props stay equal
17 const onPick = useCallback((p: Point) => setLabel(`(${p.x}, ${p.y})`), []);
18
19 return (
20 <div>
21 <Plot points={points} onPick={onPick} />
22 <p>Selected: {label}</p> {/* changing label does not re-render Plot */}
23 </div>
24 );
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app