Lesson 18 of 37Effects and beyond
Performance
Measure first, then fix slow React screens with memo, useMemo, useCallback, virtualization, and code splitting.
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 buildthennpm run preview). Development builds are much slower and run StrictMode double renders.
Put a sensible performance workflow in order.
- Tap the steps below in the right order.
Why components re-render
A component re-renders when:
- its own state changes,
- its parent re-renders (by default, children re-render too, whether or not their props changed), or
- 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.
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.
Without memo, every keystroke re-renders the whole subtree, including a big results list whose data did not change.
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 exactlyuseMemo(() => fn, [deps]).
Use them for two reasons only:
- Expensive calculations. Something that takes measurable time (say, more than a millisecond) such as filtering or sorting thousands of items.
- Stable identity. A value or function passed to a
memochild, or used in another hook's dependency array.
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.
useCallback actually prevent work?const handleSave = useCallback(() => save(form), [form]);
return <SaveButton onSave={handleSave} />;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 symptom to the most likely fix.
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:
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.
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 translateYCode 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.
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.
items and also itemCount in state, updating both together. What is the best change?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.
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.
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:
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
useTransitionoruseDeferredValue(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 asetTimeout) 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.
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.
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 });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 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.