Chapters 29 and 30 were about skipping work React didn't need to do. This chapter is about the work it does need to do, when there's simply too much of it: a list with 10,000 rows, a bundle that takes four seconds to download on a phone, a hero image that holds up the page, a computation that freezes the main thread for a second. Memoization can't help with any of these, because the work isn't repeated. It's just big.
The fixes share one idea: do less at once. Render only the rows on screen. Ship only the code this page needs. Load only the images the user can see, and the important one first. Move heavy computation somewhere the main thread doesn't have to wait for it.
The problem: 10,000 rows#
The reading list grew. Here it is with 10,000 entries and a filter. Watch the console when it mounts, then type into the filter.
import { useLayoutEffect, useState } from "react";
import { books } from "guide-tools";
const rows = Array.from({ length: 10_000 }, (_, i) => ({
...books[i % books.length],
id: i,
}));
export default function App() {
const start = performance.now();
const [query, setQuery] = useState("");
const visible = rows.filter((r) => r.title.toLowerCase().includes(query.toLowerCase()));
useLayoutEffect(() => {
console.log(`${visible.length} rows: ${(performance.now() - start).toFixed(0)} ms`);
});
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter" />
<div style={{ height: 300, overflow: "auto", border: "1px solid #d6d3d1" }}>
{visible.map((r) => (
<div key={r.id} style={{ height: 36, display: "flex", gap: 8, alignItems: "center" }}>
<strong>#{r.id}</strong> {r.title} <em>({r.year})</em>
</div>
))}
</div>
</div>
);
}Each keystroke rebuilds and diffs tens of thousands of elements and touches the DOM for every row that appears or disappears. Typing "r" changes thousands of rows. The user can see eight of them.
Memoization doesn't help: the filter result really does change. A transition (chapter 24) would keep the input responsive while the list catches up, which is worth doing, but the list itself would still be slow, and the browser still holds 10,000 rows of DOM, with their memory and layout cost.
The real fix is to stop rendering what nobody can see.
Build a windowed list#
Virtualization (also called windowing) renders only the rows inside the scroll viewport, plus a few extra above and below. Everything else doesn't exist in the DOM at all. To keep the scrollbar honest, an empty spacer as tall as the full list sits inside the scroll container, and each rendered row is absolutely positioned at its real offset.
With a fixed row height, the arithmetic is small:
first = Math.floor(scrollTop / rowHeight)is the first visible row.last = Math.ceil((scrollTop + viewportHeight) / rowHeight)is one past the last visible row.- Add
overscanrows on each side, so a quick scroll doesn't reveal a blank gap before React catches up. - Render rows
starttoend, each withtop: index * rowHeight, inside a spacer ofcount * rowHeight.
A 20-row list in a viewport that fits 5 rows. At scrollTop 0, rows 0 to 4 are visible. With an overscan of 2 we also render rows 5 and 6, so a small scroll never shows a blank gap. Only 7 rows exist in the DOM.
Here it is with 100,000 rows. Scroll as fast as you like, and watch the counter of rows in the DOM.
import { useState, type ReactNode } from "react";
import { books } from "guide-tools";
const rows = Array.from({ length: 100_000 }, (_, i) => ({ ...books[i % books.length], id: i }));
function VirtualList<T>({
items,
rowHeight,
height,
overscan = 3,
renderRow,
}: {
items: T[];
rowHeight: number;
height: number;
overscan?: number;
renderRow: (item: T, index: number) => ReactNode;
}) {
const [scrollTop, setScrollTop] = useState(0);
const first = Math.floor(scrollTop / rowHeight);
const last = Math.ceil((scrollTop + height) / rowHeight);
const start = Math.max(0, first - overscan);
const end = Math.min(items.length, last + overscan);
const rendered = [];
for (let i = start; i < end; i++) {
rendered.push(
<div key={i} style={{ position: "absolute", top: i * rowHeight, height: rowHeight, left: 0, right: 0 }}>
{renderRow(items[i], i)}
</div>
);
}
return (
<>
<p>Rows in the DOM: {end - start} of {items.length.toLocaleString()}</p>
<div
style={{ height, overflow: "auto", position: "relative", border: "1px solid #d6d3d1" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * rowHeight }}>{rendered}</div>
</div>
</>
);
}
export default function App() {
return (
<VirtualList
items={rows}
rowHeight={36}
height={300}
renderRow={(r) => (
<div style={{ display: "flex", gap: 8, alignItems: "center", height: "100%" }}>
<strong>#{r.id}</strong> {r.title} <em>({r.year})</em>
</div>
)}
/>
);
}A hundred thousand rows, and the DOM never holds more than about 16 rows. The cost of each scroll is a handful of row renders, no matter where you are in the list. (The 100,000-object array itself costs memory, but plain objects are cheap compared to DOM nodes.)
The toy skips the parts that make production virtualization hard:
- Variable row heights. Real rows wrap text and load images. You need an estimated size, then measure rows after they render and correct the offsets, without making the scroll position jump.
- Scrolling to an item, restoring scroll position after navigation, sticky headers, horizontal and grid layouts, and reverse lists for chat.
- Accessibility and browser features. Rows that aren't in the DOM can't be found with the browser's find-in-page, aren't read by screen readers, and can't receive focus. Good libraries help with ARIA attributes such as
aria-setsizeandaria-posinset, and keyboard navigation has to move focus as rows mount.
The real thing: TanStack Virtual and react-window#
In production, use a library. The two common ones map directly onto the toy.
TanStack Virtual (@tanstack/react-virtual) is headless: a hook computes the window and you render the markup. count, estimateSize and overscan are the toy's inputs; getTotalSize() is the spacer; each virtual item's start is the toy's index * rowHeight. Passing measureElement as a ref lets it measure real heights, which handles variable-height rows.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function BookList({ books }: { books: { id: number; title: string }[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: books.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 36,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((item) => (
<div
key={item.key}
data-index={item.index}
ref={virtualizer.measureElement}
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${item.start}px)` }}
>
{books[item.index].title}
</div>
))}
</div>
</div>
);
}react-window is a component instead of a hook. Its current major version (2) renders a List from a rowComponent, a rowCount and a rowHeight, passes each row an index and the style that positions it, and forwards anything in rowProps:
import { List, type RowComponentProps } from "react-window";
function Row({ index, style, books }: RowComponentProps<{ books: { title: string }[] }>) {
return <div style={style}>{books[index].title}</div>;
}
export function BookList({ books }: { books: { title: string }[] }) {
return <List rowComponent={Row} rowCount={books.length} rowHeight={36} rowProps={{ books }} />;
}Virtualize when a list can grow into the hundreds of complex rows or thousands of simple ones, and measure first (chapter 28): a 200-row list usually doesn't need it, and virtualization costs you find-in-page and some accessibility work.
Ship less code#
The second kind of "big" is the bundle. Before a client-rendered React app can show anything interactive, the browser has to download, parse, compile and run its JavaScript. On a mid-range phone, parsing and compiling a large bundle can take seconds, which shows up as slow LCP and, while the main thread is busy, slow INP.
Route-level code splitting#
Chapter 26 introduced lazy and Suspense: lazy(() => import("./Chart")) turns a dynamic import() into a component, and the bundler puts that module (and everything only it imports) in a separate file, loaded the first time the component renders. Suspense shows a fallback meanwhile.
The question at scale is where to split. A good default strategy:
- Split by route. A user on
/booksdoesn't need the code for/settingsor/admin. Routes are natural boundaries: they're large, they're visited separately, and a loading state during navigation feels normal. Frameworks do this for you: Next.js splits per route automatically, and React Router and TanStack Router support lazy route modules. - Split heavy, rarely used widgets: rich text editors, charts, maps, PDF viewers, a big modal, anything behind a tab or a click.
- Don't split small components. Every split is an extra request and a loading state. Splitting a 2 KB button makes things slower.
- Start loading before the click. Call the same
import()on hover or focus, or when the browser is idle, so the code is often ready by the time the user commits. The browser caches each module once it's loaded, so whenlazylater calls the sameimport(), it resolves from that load instead of fetching again. (The sandbox below also keeps one shared promise, so the simulated delay is paid once.)
Here's the last point in action. The "chart" module takes 800 ms to arrive (simulated with sleep). Click Show stats straight away and you see the fallback. Reload, hover over the button for a second first, then click: it's instant.
import { Suspense, lazy, useState } from "react";
import { sleep } from "guide-tools";
// One shared promise: hovering and rendering both use it.
let chartModule: Promise<typeof import("./Chart")> | undefined;
function loadChart() {
chartModule ??= sleep(800).then(() => import("./Chart"));
return chartModule;
}
const Chart = lazy(loadChart);
export default function App() {
const [open, setOpen] = useState(false);
return (
<div>
<button onMouseEnter={loadChart} onFocus={loadChart} onClick={() => setOpen(true)}>
Show stats
</button>
{open ? (
<Suspense fallback={<p>Loading chart code…</p>}>
<Chart />
</Suspense>
) : null}
</div>
);
}React's own resource preloading APIs (preload, preinit and friends) are another way to start loads early. They work on the client too, and chapter 43 covers them alongside server rendering.
Find out what's in the bundle#
You can't shrink what you haven't looked at. A bundle analyzer draws your output as a treemap, every module a rectangle sized by its bytes, and shows why each module was included.
- Next.js 16.1+ with Turbopack:
npx next analyzeopens an interactive analyzer with import chains for client and server modules, and--outputwrites it to disk for before-and-after comparisons. Webpack builds use@next/bundle-analyzerwithANALYZE=true npm run build. - Vite: add a Rollup-compatible visualizer plugin such as
rollup-plugin-visualizerto the build. - Any bundler:
source-map-explorerreads the production bundle and its source maps.
What to look for, roughly in order of payoff:
- One giant dependency used for one small thing: a full date library for one format call, all of lodash for
debounce, an icon package imported whole. Replace it, import the specific module, or use a platform API (Intl.DateTimeFormat). - Duplicates: two versions of the same library, pulled in by different dependencies.
- Code that should be split: an editor or chart in the main bundle when it's only used on one page.
- Code that shouldn't be on the client at all. In a Server Components app (Part 7), libraries that only turn data into markup (markdown, syntax highlighting) can run on the server and never ship.
Then set a budget: a size limit per route that CI checks, so the bundle doesn't quietly grow back.
Images#
Images are usually the largest bytes on a page, and very often the LCP element. A few attributes fix most image problems, with plain <img> or a framework component:
export function Hero() {
return (
<>
{/* The LCP image: load it now, at high priority, at the right size. */}
<img
src="/covers/hero-800.avif"
srcSet="/covers/hero-400.avif 400w, /covers/hero-800.avif 800w, /covers/hero-1600.avif 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width={800}
height={450}
fetchPriority="high"
alt="Shelves of books"
/>
{/* Below the fold: let the browser wait until it's close to the viewport. */}
<img src="/covers/dune.webp" width={200} height={300} loading="lazy" decoding="async" alt="Dune cover" />
</>
);
}- Always set
widthandheight(or a CSSaspect-ratio). The browser reserves the space before the image arrives, so nothing shifts: that's CLS. - Lazy-load below the fold with
loading="lazy", and never lazy-load the LCP image: lazy loading delays exactly the image the metric is waiting for. - Prioritize the LCP image with
fetchPriority="high"(camelCase in React). - Serve the right size and format:
srcSetandsizeslet the browser pick a file for the screen, and AVIF or WebP are much smaller than JPEG or PNG. - Next.js
<Image>does resizing, modern formats, lazy loading and reserved space for you. In Next.js 16 the oldpriorityprop is deprecated: useloading="eager"(andfetchPriority="high") for an above-the-fold image, orpreloadwhen the browser should start fetching it before it even sees the<img>.
Keep the main thread free#
The last kind of big is computation. JavaScript on a page runs on one main thread, which also handles input, layout and paint. While a function runs, nothing else does.
Recap: useDeferredValue and transitions#
Chapter 24's tools help when the expensive work is React rendering. useDeferredValue(query) lets the input render with the new value immediately while the slow list re-renders in the background with the deferred value. Because React renders concurrently, that background render can be interrupted when the user types again.
const deferredQuery = useDeferredValue(query);
// The input uses `query`; the slow list uses `deferredQuery`.
const isStale = query !== deferredQuery;The catch: React can only interrupt between components. If one component, or one event handler, runs a single 800 ms function (parsing a large file, sorting a million rows, building a search index), there's no point at which React can yield. The main thread is blocked until it returns. Transitions reorder work; they don't make it disappear.
Web workers#
A web worker runs JavaScript on a separate thread. It has no DOM and can't run React, but it can do any pure computation, and the main thread stays free to respond to input while it works. You talk to it with messages: worker.postMessage(data) sends, self.onmessage receives, and the reply comes back the same way.
In this sandbox, both buttons do 800 ms of busy work. The clock is updated every 100 ms from the main thread, and the input is there for you to type into. Click On the main thread and both freeze. Click In a worker and they don't.
import { useEffect, useRef, useState } from "react";
import { slowDown } from "guide-tools";
// The worker's code. In a real app this is its own file:
// new Worker(new URL("./crunch.worker.ts", import.meta.url), { type: "module" })
const workerSource = `
self.onmessage = (event) => {
const end = performance.now() + event.data.ms;
while (performance.now() < end) {} // pretend: parse a huge file
self.postMessage("done in a worker");
};
`;
function makeWorker() {
const url = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
return new Worker(url);
}
export default function App() {
const [ticks, setTicks] = useState(0);
const [status, setStatus] = useState("idle");
const worker = useRef<Worker | null>(null);
useEffect(() => {
const id = setInterval(() => setTicks((t) => t + 1), 100);
try {
worker.current = makeWorker();
worker.current.onmessage = (e) => setStatus(e.data);
} catch {
setStatus("workers are blocked in this browser frame");
}
return () => {
clearInterval(id);
worker.current?.terminate();
};
}, []);
return (
<div>
<p>Clock: {(ticks / 10).toFixed(1)} s</p>
<input placeholder="Type while it works" />
<p>
<button
onClick={() => {
setStatus("working on the main thread…");
setTimeout(() => {
slowDown(800);
setStatus("done on the main thread");
}, 0);
}}
>
On the main thread
</button>{" "}
<button
onClick={() => {
setStatus("working in a worker…");
worker.current?.postMessage({ ms: 800 });
}}
>
In a worker
</button>
</p>
<p>Status: {status}</p>
</div>
);
}What workers are good for, and what they cost:
- Good fits: parsing and transforming large data (CSV, JSON, Markdown), search indexing and fuzzy matching over big lists, image and audio processing, diffing, compression, cryptography, and WebAssembly modules.
OffscreenCanvaslets a worker draw to a canvas too. - Messages are copied.
postMessageuses the structured clone algorithm, so sending a 50 MB object costs a copy on each side. TransferArrayBuffers instead of copying them when you can, and send results that are already shaped for rendering. - The API is low-level. Libraries like Comlink wrap a worker so you can call its functions as async functions. Bundlers support the
new Worker(new URL("./file", import.meta.url), { type: "module" })pattern, so a worker can be an ordinary module in your project. - React stays on the main thread. The usual pattern is a hook that posts input to the worker and stores the result in state, often combined with a transition or deferred value for the render that follows.
Pitfalls#
Check your understanding#
BookRows renders all 5,000 rows. Make it render only the rows in view (plus a little overscan), keeping the scrollbar the right size, so that scrolling to row 2,000 shows "Row 2000" with fewer than 40 rows in the DOM. Keep each row's data-row attribute. Press Check when it works.
import { useState } from "react";
const ROW_HEIGHT = 30;
const HEIGHT = 300;
const COUNT = 5000;
function BookRows() {
const [scrollTop, setScrollTop] = useState(0);
const rows = [];
// TODO: only render the rows near the viewport.
for (let i = 0; i < COUNT; i++) {
rows.push(
<div key={i} data-row={i} style={{ height: ROW_HEIGHT }}>
Row {i}
</div>
);
}
return (
<div
id="scroller"
style={{ height: HEIGHT, overflow: "auto", position: "relative" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
{rows}
</div>
);
}
export default function App() {
return <BookRows />;
}A search box filters a list. The component calls const deferred = useDeferredValue(query) and then const results = buildIndexAndSearch(allBooks, deferred), where buildIndexAndSearch is a single synchronous function that takes 600 ms. Does typing stay smooth? What would you change?
Your client-rendered app's main bundle is 1.4 MB. Which split is the best first move?
A page's LCP element is its hero image, rendered with loading='lazy' and no width or height. What should change?
An interviewer asks: "You need to show 100,000 rows that users can filter and sort, in a React app that must stay responsive on mid-range phones. How do you design it?" Answer in about a minute.
Interview angle
When a UI is slow because the necessary work is big, memoization doesn't help, so I do less at once. Long lists get virtualized: only the rows in the viewport plus some overscan are rendered, inside a spacer as tall as the full list. Bundles get split by route first, then heavy widgets, with loading started on hover, and I check an analyzer for big or duplicated dependencies. Images get dimensions, below-the-fold ones are lazy, and the LCP image loads eagerly at high priority. Heavy computation goes to a web worker, because transitions only make rendering interruptible, not a single long function.
How does list virtualization work, and what are its trade-offs?
How do you decide where to code split a React app?
Your bundle doubled in size this quarter. How do you find out why and stop it happening again?
How do images affect Core Web Vitals, and what do you do about it?
When would you use a web worker instead of useDeferredValue or startTransition?
Design a table that shows 100,000 filterable, sortable rows and stays responsive on a mid-range phone.
Recap#
- Some UIs are slow because the necessary work is big, not repeated. Memoization can't help; doing less at once can.
- Virtualization renders only the rows in the viewport plus overscan, inside a spacer the height of the full list. Use TanStack Virtual or react-window in production, and mind keys, variable heights and accessibility.
- Split code by route first, then heavy widgets, and start loading on hover or idle. Look at the bundle with an analyzer (
next analyze, a Rollup visualizer, source-map-explorer) and set budgets. - Give images dimensions, lazy-load what's below the fold, and load the LCP image eagerly with high priority.
- Transitions and
useDeferredValuemake rendering interruptible, but a single long function still blocks. Move heavy computation to a web worker.
Sources#
- react.dev:
lazyanduseDeferredValue - react.dev:
<img> - TanStack Virtual: React Virtual
- react-window: README
- Next.js: Optimizing package bundling and the Image component
- web.dev: Optimize Largest Contentful Paint and content-visibility
- MDN: Using Web Workers
- Facts checked November 24, 2026.