Sub topic 2
Measure before you optimize
Virtualization adds code, edge cases, and accessibility costs. Before you add it, confirm that the list is the problem, and record a number you can compare against afterward. This chapter shows how to take that measurement.
This chapter assumes you know React function components, the useState and useRef hooks, and how to open your browser's developer tools. You do not need any virtualization code yet.
What "slow" means for a list
A long list can be slow in three different ways. Each one has a different cause and a different fix.
| Symptom | What the user sees | Usual cause |
|---|---|---|
| Slow first render | A blank or frozen page after navigation | React creates thousands of elements, and the browser builds thousands of DOM nodes |
| Slow updates | Typing in a filter box lags | Every keystroke re-renders every row |
| Janky scrolling | Frames drop while scrolling | Heavy rows, large layout and paint work, or scroll handlers that do too much |
Virtualization mainly fixes the first two, because it keeps the number of mounted rows small. It does not fix a row that is expensive on its own. If one row takes 20 ms to render, rendering 15 visible rows still takes 300 ms.
So the first question is not "how many rows do I have?" It is "which of these three symptoms do I have, and where does the time go?"
A baseline you can reproduce
A baseline is a measurement taken before any change. You will compare every later change against it. To be useful, it needs a fixed data size and a repeatable action.
The component below renders a configurable number of rows and logs how long the first render takes, from the render call to the browser's next paint. It uses performance.now(), which returns a timestamp in milliseconds.
import { useLayoutEffect, useState } from "react";
type Row = { id: number; label: string };
function makeRows(count: number): Row[] {
return Array.from({ length: count }, (_, i) => ({
id: i,
label: `Row ${i}`,
}));
}
export function PlainList({ count }: { count: number }) {
const [rows] = useState(() => makeRows(count));
useLayoutEffect(() => {
const start = performance.now();
requestAnimationFrame(() => {
// Runs just before the next paint.
setTimeout(() => {
// Runs after that paint has been issued.
const elapsed = performance.now() - start;
console.log(`${count} rows: ${elapsed.toFixed(1)} ms to next paint`);
}, 0);
});
}, [count]);
return (
<ul style={{ height: 400, overflow: "auto" }}>
{rows.map((row) => (
<li key={row.id} style={{ height: 35 }}>
{row.label}
</li>
))}
</ul>
);
}This measures only the time after React has committed to the DOM, so it undercounts the React render step itself. That is fine for a rough comparison. For a full picture, use the two tools in the next sections.
Try it with count set to 100, 1,000, 10,000, and 50,000. Run each size several times and take the median, because the first run includes cold code and cache effects. If the time grows roughly in proportion to the row count, the cost is per row, which is exactly the case virtualization addresses.
Measure with the browser Performance panel
The Performance panel in Chrome, Edge, or Firefox shows where each millisecond went. Use it for both load and scroll problems.
- Open DevTools and select the Performance tab.
- Turn on CPU throttling (for example, 4x slowdown). Your development machine is faster than many users' devices, and throttling makes problems visible.
- Start recording, perform one action (load the page, type in the filter, or scroll for three seconds), and stop recording.
- Read the main thread flame chart. Look for long tasks, which the browser marks with a red corner when they run longer than 50 ms.
Within a long task, the colors tell you which kind of work dominates:
- Yellow is JavaScript, including React rendering.
- Purple is style recalculation and layout.
- Green is paint and compositing.
A list with many DOM nodes often shows a large purple block, because the browser must calculate styles and positions for every node. A list with expensive row components shows mostly yellow. This distinction matters. Heavy yellow in a single row component points to optimizing that component, not to virtualizing.
Also check the frames row during scrolling. Frames that miss the 16.7 ms budget (60 frames per second) show up as red or long bars. If scrolling is smooth but the first load is slow, the problem is mounting cost, not scroll cost.
Measure React renders with the Profiler
The browser panel shows total time but not which React components caused it. React DevTools has a Profiler tab for that. For code-level measurement, React also exports a Profiler component that reports render timing for the subtree it wraps.
import { Profiler, useState } from "react";
import type { ProfilerOnRenderCallback } from "react";
const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration) => {
console.log(`${id} ${phase}: ${actualDuration.toFixed(1)} ms`);
};
export function FilterableList({ items }: { items: string[] }) {
const [query, setQuery] = useState("");
const visible = items.filter((item) => item.includes(query));
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Filter"
/>
<Profiler id="list" onRender={onRender}>
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</Profiler>
</div>
);
}The callback receives the phase ("mount" or "update") and actualDuration, the time spent rendering the wrapped tree for that commit. Type in the input and watch the log. If every keystroke produces an update costing tens of milliseconds, the list re-renders too much work per interaction.
Two cautions apply:
- Development builds are much slower than production builds, and
Profilertimings are only collected in development or in a special profiling build. Use numbers from the development build to compare before and after, not as absolute figures. - React Strict Mode renders components twice in development, which can inflate the numbers. Keep it on for correctness, but be aware of it when reading the results.
Count the DOM nodes
The number of DOM nodes is a simple proxy for the cost the browser pays. You can read it directly in the console:
document.querySelectorAll("*").length;Pages with more than roughly 1,500 nodes start to receive warnings from tools such as Lighthouse, and each extra node adds style and layout cost. A row with a wrapper, an avatar, a title, a subtitle, and two buttons may contribute ten nodes. At 10,000 rows, that is 100,000 nodes.
To count the nodes in just the list, scope the query to its container:
document.querySelector("ul").querySelectorAll("*").length;Record this number in your baseline. After virtualizing, it should stay roughly constant as the data grows, and that is the clearest sign that windowing works.
Decide whether to virtualize
Use the measurements to choose a path. The table maps common findings to a next step.
| Finding | Likely next step |
|---|---|
| Under a few hundred simple rows, no long tasks | Do nothing |
| Slow updates, but each row is cheap and rows are stable | Memoize rows with `React.memo`, or lift state so fewer rows re-render |
| One row component dominates the flame chart | Optimize that row first |
| Many thousands of rows, large DOM node count, long mount task | Virtualize |
| Moderately long list, layout cost dominates | Try CSS `content-visibility`, covered in a later chapter |
| Users need page numbers or deep links to positions | Consider pagination |
These choices are not exclusive. A virtualized list with an expensive row still needs row optimization.
Common mistakes
- Measuring only once. Timings vary between runs. Take at least five and use the median.
- Measuring on a fast machine without throttling. A problem that is invisible on your laptop can freeze a mid-range phone.
- Using the development build for absolute claims. Development mode adds checks that production does not have. Confirm final results in a production build.
- Optimizing the wrong layer. Slow scrolling caused by a heavy scroll handler or large images is not fixed by virtualization alone.
- Forgetting the after measurement. If you do not repeat the exact baseline test, you cannot show that the change helped.
Record your baseline
Before moving on, write down the following for your list, at a fixed size such as 10,000 rows:
- Time to next paint on first render (median of five runs).
- Profiler
actualDurationfor one filter keystroke. - DOM node count inside the list.
- Whether scrolling drops frames under 4x CPU throttling.
You will compare these numbers against the same measurements after building the virtual list in later chapters.
Exercise
A list of 20,000 rows loads slowly. In the Performance panel, the long task is mostly purple (style and layout), and no single row component stands out in the Profiler. The DOM node count inside the list is about 200,000. Which optimization does this evidence point to, and why would memoizing the rows probably not be enough?
Show answer
It points to virtualization, because the cost comes from the number of DOM nodes the browser must style and lay out, not from slow JavaScript in one row. Memoizing rows with React.memo only avoids repeated React renders on updates. The 200,000 nodes would still be created on mount and still be laid out, so the first-load cost would remain.
Exercise
You change a list to render only 30 rows and the first render drops from 900 ms to 40 ms. Name two things you must verify before concluding that virtualization caused the improvement.
Show answer
Verify that the before and after measurements used the same build type (development or production), the same data size, the same CPU throttling, and the same action, and that you used the median of several runs rather than a single run. Any of these differences could explain part of the change.