Skip to content

Lesson 18 of 37Effects and beyond

Performance

Measure first, then fix slow React screens with memo, useMemo, useCallback, virtualization, and code splitting.

19 min read0/6 questions

Most React apps are fast enough by default. When one is not, the fix is rarely "add useMemo everywhere": it is finding the one component that renders 2,000 rows on every keystroke. Teams care about this because slow typing and janky scrolling are what users actually notice, and interviewers use memo versus useCallback to check whether you understand re-renders or just copy patterns.

Measure first

Never optimize by guessing. Use the tools:

  • React DevTools Profiler. Install the React Developer Tools browser extension, open the Profiler tab, press record, do the slow thing, stop. You get a flame chart of every commit showing which components rendered, how long each took, and (if you enable it in settings) why each one rendered.
  • "Highlight updates when components render" in the DevTools settings flashes a border around everything that re-renders. Surprising flashes are your first lead.
  • Chrome Performance panel. Shows long tasks on the main thread. React 19.2 adds its own tracks there (Scheduler and Components) so you can line React work up with everything else.
  • Profile a production build (npm run build then npm run preview). Development builds are much slower and run StrictMode double renders.
Put it in order4 steps

Put a sensible performance workflow in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Why components re-render

A component re-renders when:

  1. its own state changes,
  2. its parent re-renders (by default, children re-render too, whether or not their props changed), or
  3. a context it reads changes.

Rule 2 is where most waste comes from. Often the cheapest fix is structural, not a hook: move state down into the small component that uses it, or pass expensive children as children so they are created by a parent that does not re-render.

// Before: typing re-renders the whole page, including <ExpensiveChart />
function Page() {
  const [query, setQuery] = useState("");
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <ExpensiveChart />
    </>
  );
}
 
// After: the state lives in a small component; the chart never re-renders on typing
function Page() {
  return (
    <>
      <SearchInput />
      <ExpensiveChart />
    </>
  );
}

memo: skip a render when props are equal

memo(Component) returns a version that skips re-rendering when every prop is the same as last time, compared with Object.is. Open the console and click the button: the plain child logs every time, the memoized one does not.

ReactMemoDemo.tsx
import { memo, useState } from "react"; function PlainChild({ name }: { name: string }) { console.log("PlainChild rendered"); return <p>Plain: {name}</p>;} const MemoChild = memo(function MemoChild({ name }: { name: string }) { console.log("MemoChild rendered"); return <p>Memo: {name}</p>;}); export default function App() { const [count, setCount] = useState(0); return ( <div> <button onClick={() => setCount(count + 1)}>Parent count: {count}</button> <PlainChild name="Ada" /> <MemoChild name="Ada" /> </div> );}

memo only helps if the props really are equal. Objects, arrays, and functions created during render are new every time, so <MemoChild style={{ color: "red" }} /> or onClick={() => ...} defeats it. That is what the next two hooks are for.

Typing in a search box
SearchPagequery stateSearchInputRow 1Row 2ResultsListmemo, props: items, onSelectSidebarroot

Without memo, every keystroke re-renders the whole subtree, including a big results list whose data did not change.

1/3

useMemo and useCallback

  • useMemo(() => compute(a, b), [a, b]) caches a value and recomputes it only when a dependency changes.
  • useCallback(fn, [deps]) caches a function. It is exactly useMemo(() => fn, [deps]).

Use them for two reasons only:

  1. Expensive calculations. Something that takes measurable time (say, more than a millisecond) such as filtering or sorting thousands of items.
  2. Stable identity. A value or function passed to a memo child, or used in another hook's dependency array.
ReactUseMemoDemo.tsx
import { useMemo, useState } from "react"; const NUMBERS = Array.from({ length: 200_000 }, (_, i) => i); export default function App() { const [divisor, setDivisor] = useState(7); const [dark, setDark] = useState(false); const count = useMemo(() => { const start = performance.now(); const result = NUMBERS.filter((n) => n % divisor === 0).length; console.log(`filtered in ${(performance.now() - start).toFixed(1)} ms`); return result; }, [divisor]); return ( <div style={{ background: dark ? "#222" : "#fff", color: dark ? "#fff" : "#222", padding: 12 }}> <label> Divisor <input type="number" value={divisor} min={1} onChange={(e) => setDivisor(Number(e.target.value) || 1)} /> </label> <p>{count} numbers are divisible by {divisor}</p> <button onClick={() => setDark(!dark)}>Toggle theme (no recompute)</button> </div> );}

Toggling the theme re-renders the component but skips the filter, because divisor did not change.

When they do not help: wrapping cheap work (a + b, a 10-item map), memoizing a callback passed to a plain <button> (DOM elements do not care about identity), or memoizing a prop for a child that is not wrapped in memo. Each hook costs a little memory and a dependency comparison, and adds noise.

Quick check
When does this useCallback actually prevent work?
const handleSave = useCallback(() => save(form), [form]);
return <SaveButton onSave={handleSave} />;
Need a nudge? A hint rules out a wrong answer.

The React Compiler

Writing memo, useMemo, and useCallback by hand is tedious and easy to get wrong. The React Compiler (stable since late 2025) is a build-time plugin that analyses your components and inserts the memoization automatically, at a finer grain than you would by hand. You enable it with babel-plugin-react-compiler in Vite, or reactCompiler: true in Next.js.

It relies on your code following the rules of React: pure render functions, no mutating props or state, hooks at the top level. In a compiled codebase you rarely write these hooks yourself; you still need to understand them for older code, for libraries, and for the cases the compiler skips. The linter (eslint-plugin-react-hooks) now includes compiler-powered rules that flag code it cannot optimize.

Match the pairs0/5 matched

Match the symptom to the most likely fix.

Choose an item, then its match on the other side.

React Compiler 1.0 in practice

React Compiler 1.0 has been stable since October 2025, and new Next.js and Vite templates offer it at setup. Here is what turning it on in an existing codebase actually involves.

Setup. The compiler is a Babel plugin, babel-plugin-react-compiler, that runs before your bundler sees the code. In Next.js 16 you install it and set one option:

next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  reactCompiler: true,
};
 
export default nextConfig;

In Vite you register the Babel plugin through the React plugin. The exact option has moved between @vitejs/plugin-react versions, so copy it from the React Compiler installation page for your version rather than from an old post. React 17 and 18 apps can use it too, with the react-compiler-runtime package and a target option.

Lint first. The compiler's analysis also ships as rules in eslint-plugin-react-hooks; the recommended preset turns them on. They flag the code the compiler cannot safely optimize: setting state during render, reading or writing refs during render, mutating props or values after they were rendered, components defined inside other components, and libraries whose APIs are known not to work with memoization. Fix what the linter reports before enabling the compiler, and keep the rules on afterwards. Any component the compiler cannot prove safe is skipped silently and keeps working unoptimized, so the linter is the only place you hear about it.

Roll out gradually on a big codebase. Set compilationMode: "annotation" and only components with a "use memo" directive at the top of their body are compiled. Opt in one feature at a time, measure, then switch to compiling everything.

Opt out when needed. If a compiled component misbehaves, put "use no memo" as the first statement of that function. It is an escape hatch while you find the real cause, usually code that breaks the rules of React and happened to work because it re-ran on every render. Leave a comment with a ticket so it does not become permanent.

function LegacyChart({ data }: Props) {
  "use no memo"; // TODO(PERF-412): chart lib mutates `data` in place; fix and remove
  // ...
}

Check it worked. In React DevTools, compiled components show a Memo badge with a sparkle next to their name. In the Profiler, unrelated updates should stop lighting up those components.

Keep your existing useMemo and useCallback for now. The compiler works with them, and deleting them in bulk can change what it produces. Write new code without manual memoization, and remove old hooks only when you touch the code and can test it.

What it does not fix. The compiler removes wasted renders: work whose result would be the same. It does nothing for renders that are genuinely needed but slow:

  • Rendering 10,000 rows is still slow. You still need virtualization.
  • A slow calculation whose inputs change on every keystroke still runs on every keystroke. You need a transition, a deferred value, a worker, or a better algorithm.
  • A heavy bundle still downloads. You still need code splitting.
  • A request waterfall is still a waterfall. That is a data problem, not a rendering one.
  • A context whose value changes still re-renders every consumer. The compiler can keep the value object stable when its contents have not changed, but it cannot narrow which consumers update.
Quick check
A team turns on the React Compiler. Which problem is it most likely to fix on its own?
Need a nudge? A hint rules out a wrong answer.

Long lists: virtualization

Rendering 10,000 rows creates 10,000 DOM nodes, which is slow no matter how well you memoize. Virtualization (or windowing) renders only the rows in view plus a small buffer, and swaps them as you scroll. Libraries: TanStack Virtual and react-window.

import { useVirtualizer } from "@tanstack/react-virtual";
 
const virtualizer = useVirtualizer({
  count: rows.length,
  getScrollElement: () => scrollRef.current,
  estimateSize: () => 36, // px per row
});
// Render only virtualizer.getVirtualItems(), positioned with translateY

Code splitting with lazy

Your bundler can split the app into chunks that load on demand. lazy(() => import("./Chart")) creates a component whose code downloads the first time it renders. While it loads, the nearest <Suspense> shows its fallback. Use it for routes, modals, and heavy widgets the user may never open.

ReactLazyChart.tsx
import { lazy, Suspense, useState } from "react"; // In a real app: lazy(() => import("./Chart")). Here we fake a slow download.const Chart = lazy( () => new Promise<{ default: React.ComponentType }>((resolve) => setTimeout(() => resolve({ default: () => <p>Chart loaded: ▁▃▅▇▅▃▁</p> }), 1000) )); export default function App() { const [isOpen, setIsOpen] = useState(false); return ( <div> <button onClick={() => setIsOpen(true)}>Show chart</button> {isOpen && ( <Suspense fallback={<p>Loading chart code...</p>}> <Chart /> </Suspense> )} </div> );}

Avoid unnecessary state

The fastest render is one that never happens. Before adding state, ask whether you can compute it from existing props or state during render. Duplicated state (a filteredItems copy of items, a fullName next to firstName and lastName) needs syncing, causes extra renders, and goes stale.

Quick check
A component stores items and also itemCount in state, updating both together. What is the best change?
Need a nudge? A hint rules out a wrong answer.

Profiling with the Profiler and Performance Tracks

"Measure first" is easy to say. Here is what a useful profiling session looks like.

1. Record the slow interaction in the React DevTools Profiler. Turn on "Record why each component rendered while profiling" in the Profiler settings first. Each bar along the top is one commit; tall bars are slow commits. Click the slowest.

2. Read the flame chart, then the ranked chart. The flame chart shows the tree for that commit: grey components did not render, coloured ones did, and the width is time spent including children. The ranked view sorts components by their own render time, which is usually where the answer is. Hover a component to see why it rendered: "Props changed: onSelect", "Context changed", "The parent component rendered", or "Hook 3 changed".

3. Ask what the reason means. "Props changed: onSelect" on a memo component means a new function each render: an unstable callback. "The parent component rendered" on 500 rows means state lives too high. "Context changed" across the app means a context holding too much.

4. Switch to the Chrome Performance panel for the full picture. React's work is only part of an interaction. The browser also runs your event handlers, style and layout, and paint. React's Performance Tracks (since 19.2) put its Scheduler and Components tracks in the same timeline as everything else, so you can see whether a long task was React rendering, a slow handler, or layout. Record with CPU throttling (4x or 6x slowdown) to approximate a mid-range phone, because your laptop hides problems your users feel.

5. Measure in production too. DevTools only show your machine. The <Profiler> component reports render timings from real sessions:

import { Profiler, type ProfilerOnRenderCallback } from "react";
 
const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration, baseDuration) => {
  // actualDuration: time spent rendering this commit (lower when memoization works)
  // baseDuration: estimated time to render the whole subtree with no memoization
  if (actualDuration > 16) analytics.track("slow-render", { id, phase, actualDuration });
};
 
<Profiler id="ProductGrid" onRender={onRender}>
  <ProductGrid />
</Profiler>;

onRender is a no-op in a normal production build, to keep it fast. To use it in production, ship the profiling build of React DOM (Next.js has next build --profile; other setups alias react-dom/client to react-dom/profiling), and sample a small share of sessions, since profiling adds overhead. Compare actualDuration with baseDuration: if they are close, memoization is not helping this subtree.

Measuring INP

Interaction to Next Paint (INP) is the Core Web Vital for responsiveness, and the one React code affects most directly. For each click, tap, or key press, it measures the time from the input until the browser paints the next frame. The page's INP is roughly its worst interaction. Google's thresholds: 200 ms or less is good, over 500 ms is poor, judged at the 75th percentile of real page visits.

The three parts of one interaction
  1. Input delaythe main thread is busy with something else when the user clicks
  2. Processing timeyour event handlers run, then React renders and commits
  3. Presentation delaystyle, layout, and paint of the new frame

Input delay: if a long task (a big render, a hydration chunk, a third-party script) is running when the user clicks, the click waits. Fix: break up long tasks, defer non-urgent work, hydrate less.

1/4

Lab tools only show your machine, so collect INP from real users with the web-vitals library. Its attribution build tells you which element was slow and which part of the interaction took the time:

src/vitals.ts
import { onINP } from "web-vitals/attribution";
 
onINP(({ value, rating, attribution }) => {
  sendToAnalytics({
    metric: "INP",
    value,          // milliseconds
    rating,         // "good" | "needs-improvement" | "poor"
    target: attribution.interactionTarget, // a CSS selector for the element
    inputDelay: attribution.inputDelay,
    processing: attribution.processingDuration,
    presentation: attribution.presentationDelay,
  });
});

In React, the usual causes of poor INP and their fixes:

  • A keystroke re-renders a large tree. Move state down, or keep the input update urgent and render the results with useTransition or useDeferredValue (Transitions and Suspense), so React can paint the keystroke first.
  • A click handler does heavy synchronous work before React even renders. Do the minimum to update the UI, then yield (for example with await scheduler.yield() where supported, or a setTimeout) before analytics, logging, or other non-urgent work.
  • Hydration of a big page blocks the main thread while the user tries to tap. Server Components and smaller client components mean less to hydrate.
  • Thousands of DOM nodes make every commit's layout and paint slow. Virtualize.

Context splitting and selector patterns

The Context lesson showed the rule: every component that reads a context re-renders when its value changes. On a dashboard that holds filters, the current user, and live data in one AppContext, that means every consumer re-renders when any of it changes. There are three levels of fix.

1. Split by how often things change. Put rarely changing values (user, theme, feature flags) in their own contexts, and fast-changing ones (the current filter text) in another. Components subscribe only to what they read.

2. Split state from actions. Functions to change state rarely change, so put them in a separate context from the values. Components that only trigger changes, such as a toolbar, stop re-rendering when the data moves. Context shows this pattern in detail.

3. Use a store with selectors when one object changes often and many components read different parts of it. A selector is a function that picks the part a component needs ((state) => state.filters.search). The store notifies subscribers on every change, but each component re-renders only if its selected value changed. Zustand, Redux Toolkit (useSelector), and Jotai work this way, all built on useSyncExternalStore.

The demo puts the same state in a context and in a tiny selector store. Type in each box and watch which components log.

ReactContextVsSelector.tsx
import { createContext, useContext, useState, useSyncExternalStore } from "react";import type { ReactNode } from "react"; // --- Version 1: one context with two fields ---type Form = { name: string; count: number };const FormContext = createContext<{ form: Form; setName: (n: string) => void } | null>(null); function CtxName() { const ctx = useContext(FormContext)!; console.log("context: name input rendered"); return <input value={ctx.form.name} onChange={(e) => ctx.setName(e.target.value)} placeholder="Type here (context)" />;}function CtxCount() { const ctx = useContext(FormContext)!; console.log("context: count label rendered"); return <span> count: {ctx.form.count}</span>;}function CtxProvider({ children }: { children: ReactNode }) { const [form, setForm] = useState<Form>({ name: "", count: 0 }); return <FormContext value={{ form, setName: (name) => setForm({ ...form, name }) }}>{children}</FormContext>;} // --- Version 2: a store with selectors ---function createStore<T>(initial: T) { let state = initial; const listeners = new Set<() => void>(); return { get: () => state, set: (next: Partial<T>) => { state = { ...state, ...next }; listeners.forEach((l) => l()); }, subscribe: (l: () => void) => { listeners.add(l); return () => listeners.delete(l); }, };}const store = createStore<Form>({ name: "", count: 0 });function useStore<S>(selector: (s: Form) => S): S { return useSyncExternalStore(store.subscribe, () => selector(store.get()));} function StoreName() { const name = useStore((s) => s.name); console.log("store: name input rendered"); return <input value={name} onChange={(e) => store.set({ name: e.target.value })} placeholder="Type here (store)" />;}function StoreCount() { const count = useStore((s) => s.count); console.log("store: count label rendered"); return <span> count: {count}</span>;} export default function App() { return ( <div style={{ display: "grid", gap: 12 }}> <CtxProvider> <div><CtxName /><CtxCount /></div> </CtxProvider> <div><StoreName /><StoreCount /></div> </div> );}

Each keystroke in the context box logs both context components, because the whole value changed. Each keystroke in the store box logs only the store's input: the count label's selected value, count, did not change, so React skips it.

Selectors have one rule, the same one as getSnapshot in Custom Hooks: they must return the same value when nothing relevant changed. A selector like (s) => ({ name: s.name }) returns a new object every time and re-renders on every change (or loops). Select primitives, select several times, or use the library's shallow-compare helper (Zustand's useShallow, for example).

There are libraries that add selectors to context itself (use-context-selector), but at that point most teams pick a store. The order to try: split contexts, separate actions from state, then a store for hot, widely shared state.

Predict the outputJavaScript

Using the store version above, you click a button that runs store.set({ count: 1 }). Which components log a render?

function StoreName() {
const name = useStore((s) => s.name);
console.log("name");
// ...
}
function StoreCount() {
const count = useStore((s) => s.count);
console.log("count");
// ...
}

store.set({ count: 1 });
Need a nudge? Hints walk you through it.
ChallengeMedium

Stop a list from re-rendering

Every click on Clicked N times re-renders TodoList, even though the todos did not change. The list counts its own renders with a test-only counter (listRenders); keep those two instrumentation lines as they are.

Make TodoList re-render only when todos or onRemove actually change:

  • Clicking the counter button must not re-render the list.
  • Clicking Remove next to a todo still removes it.

Use memo for the component and useCallback for the handler (no React Compiler runs in this preview).

React
import { memo, useCallback, useState } from "react"; let listRenders = 0; // test-only instrumentation, keep this lineObject.assign(window, { getListRenders: () => listRenders }); // keep this line too function TodoList({ todos, onRemove,}: { todos: string[]; onRemove: (todo: string) => void;}) { listRenders += 1; return ( <ul> {todos.map((todo) => ( <li key={todo}> {todo} <button onClick={() => onRemove(todo)}>Remove</button> </li> ))} </ul> );} export default function App() { const [count, setCount] = useState(0); const [todos, setTodos] = useState(["Write tests", "Fix bug", "Ship it"]); function handleRemove(todo: string) { setTodos(todos.filter((t) => t !== todo)); } return ( <div> <button onClick={() => setCount(count + 1)}>Clicked {count} times</button> <TodoList todos={todos} onRemove={handleRemove} /> </div> );}
Key terms
React Profiler
The DevTools tab that records commits and shows which components rendered, for how long, and why.
memo
Wraps a component so it skips re-rendering when all props are equal by Object.is.
useMemo / useCallback
Cache a computed value or a function between renders until a dependency changes.
React Compiler
A build-time plugin that automatically memoizes components and values, replacing most hand-written memo hooks.
virtualization
Rendering only the visible rows of a long list and recycling them while scrolling.
code splitting
Loading parts of the bundle on demand, for example with lazy(() => import(...)) and Suspense.
"use no memo"
A directive at the top of a component or hook that tells the React Compiler to skip it. A temporary escape hatch.
INP
Interaction to Next Paint: the Core Web Vital for responsiveness, from input to the next painted frame. Good is 200 ms or less.
selector
A function that picks the part of a store a component needs, so it re-renders only when that part changes.
profiling build
A React DOM build that keeps <Profiler> timings working in production, at a small cost.