Sub topic 1
Why Long Lists Get Slow
This chapter explains where the time goes when React renders thousands of rows. It also shows how to measure that cost, so you can tell a list problem from some other problem. Later chapters build the fix.
Prerequisites
This chapter assumes you already know:
- React function components, props, and state.
- The
useState,useRef, anduseEffecthooks. - Basic CSS positioning (
relative,absolute) andoverflowscrolling. - How the browser DOM and scroll events work.
You do not need any virtualization knowledge. You do need a browser with developer tools, because the examples ask you to measure.
The naive list
Most lists start out like this:
type Item = { id: number; label: string };
export function NaiveList({ items }: { items: Item[] }) {
return (
<ul style={{ height: 400, overflow: "auto" }}>
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
);
}With 50 items this is fine. With 50,000 items, the component mounts 50,000 <li> elements, even though the 400px container shows about 12 of them at a time. The other 49,988 are scrolled out of view, and nobody sees them. The browser and React still pay for every one.
Where the cost comes from
The cost is not one thing. It is a chain of steps, and each step grows with the number of rows.
React work
On the first render, React calls your component and builds a tree of elements. It creates a fiber (React's internal work unit) for each element. This is the render phase. React then commits the result to the DOM, which is the commit phase. Both phases do work in proportion to the number of rows.
The cost returns on every update. If the parent re-renders and the rows are not memoized, React re-renders all 50,000 row components and compares their output with the previous output. Typing in a search box that sits above the list can trigger this on every keystroke.
Browser work
After React updates the DOM, the browser has to turn it into pixels. This happens in stages:
- Style calculation. The browser works out which CSS rules apply to each element.
- Layout. The browser computes the size and position of each element. Changing one element can force layout of many others.
- Paint. The browser draws each element into layers.
- Composite. The browser combines the layers on screen.
Style calculation and layout are the usual bottlenecks in a long list. Both scale with the number of nodes in the document, not with the number visible on screen.
Memory
Every DOM node is an object in memory. So is every fiber, every props object, and every event handler closure. A row with a few nested elements can easily cost several kilobytes in total. Multiplied by 50,000 rows, this adds up to hundreds of megabytes on a phone with limited memory. The tab may become slow, or the operating system may kill it.
The summary
The following table shows which part of the cost grows with which action.
| Action | What grows with row count | Typical symptom |
|---|---|---|
| First render | React render, commit, style, layout | Long blank screen or frozen page on load |
| State change in parent | Re-rendering every row | Input lag while typing |
| Inserting or removing a row | Layout of rows below it | Janky updates |
| Scrolling | Usually little, but heavy rows can slow paint | Dropped frames |
| Idle | Memory held by nodes and fibers | Tab slowdowns, crashes on low-end devices |
Notice that scrolling is often the cheapest of these. The browser scrolls an already-laid-out page on a separate thread. Slow scrolling in a long list typically means rows are expensive to paint, or JavaScript is running on scroll events.
The cost model
A useful rough model is:
total cost ≈ rows × cost per row
The cost per row includes the number of DOM nodes in the row, the complexity of its CSS, and the work in its component. A row with 3 nodes is cheap. A row with an avatar, a menu, three buttons, and tooltips may have 40 nodes. Reducing cost per row helps, but it only changes the constant. The row count remains the multiplier.
This is the key idea behind virtualization. Instead of making each row cheaper, you make the number of mounted rows small and roughly constant. If 12 rows are visible and you mount 20, the cost stays the same whether the list holds 1,000 items or 1,000,000.
Measure before you optimize
Virtualization adds complexity. It changes how the page scrolls, how search works, and how you manage state. You should confirm that list size is actually your problem before paying that price.
Measure render time with the React Profiler
React provides a Profiler component that reports how long a subtree takes to render. This example logs the cost of a list:
import { Profiler, type ProfilerOnRenderCallback } from "react";
const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration) => {
console.log(`${id} ${phase}: ${actualDuration.toFixed(1)}ms`);
};
type Item = { id: number; label: string };
export function ProfiledList({ items }: { items: Item[] }) {
return (
<Profiler id="list" onRender={onRender}>
<ul style={{ height: 400, overflow: "auto" }}>
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
</Profiler>
);
}The phase argument is "mount" or "update". The actualDuration is the time React spent rendering the subtree, in milliseconds. It does not include the browser's layout and paint time.
Measure the whole pipeline in the Performance panel
The Profiler misses browser work. For that, use the Performance panel in Chrome DevTools:
- Open DevTools and select the Performance tab.
- Click record, trigger the slow action (load the page, type in the search box, or scroll), then stop.
- Look at the main thread flame chart. Purple blocks are style and layout work. Green blocks are paint. Yellow blocks are JavaScript.
- Check for long tasks. The panel marks tasks over 50ms with a red corner.
Also check the node count. In the Console, run:
document.querySelectorAll("*").length;Google's Lighthouse guidance flags pages with more than about 1,400 DOM nodes as a warning, and about 800 nodes as the point where it starts to matter. These are guidelines, not hard limits. A page with 5,000 simple nodes may be fine. A page with 2,000 heavy nodes may not be.
Build a quick benchmark
A simple harness lets you see how cost scales. This component renders a list of a size you choose and times the mount:
import { useLayoutEffect, useState } from "react";
function makeItems(n: number) {
return Array.from({ length: n }, (_, i) => ({ id: i, label: `Row ${i}` }));
}
export function Benchmark() {
const [count, setCount] = useState(0);
const [ms, setMs] = useState<number | null>(null);
const items = makeItems(count);
const start = performance.now();
useLayoutEffect(() => {
if (count === 0) return;
// Reading offsetHeight forces the browser to finish layout first.
document.body.offsetHeight;
setMs(performance.now() - start);
}, [count]);
return (
<div>
{[1000, 10000, 50000].map((n) => (
<button key={n} onClick={() => setCount(n)}>
{n} rows
</button>
))}
<p>{ms === null ? "Pick a size" : `Mount took about ${ms.toFixed(0)}ms`}</p>
<ul>
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
</div>
);
}The start value is captured during render, and the layout effect runs after React commits to the DOM. Reading offsetHeight forces layout, so the measured time includes React's work and the browser's layout. Run it in a production build, since development builds are much slower and give misleading numbers. Expect time to grow roughly linearly with the row count.
Common mistakes when diagnosing slow lists
- Blaming the list when the rows re-render needlessly. If typing in a nearby input re-renders 5,000 rows,
React.memoon the row component and stable props may fix it without any virtualization. Check the Profiler's "why did this render" information first. - Using array index as the key. When items are inserted or removed, index keys cause React to reuse the wrong row state and to do more DOM updates than needed. Use a stable ID.
- Measuring in development mode. React's development build adds checks that make rendering several times slower.
- Ignoring cost per row. Cutting a row from 40 nodes to 10 can be a larger win than anything else, especially for lists of a few hundred items.
- Assuming scroll is the problem. Scroll handlers that call
setStateon every event can cause many renders per second. The list itself may be innocent.
When the cost is a real problem
As a rough decision aid:
- Under a few hundred simple rows: do nothing. The cost is negligible.
- A few hundred to a few thousand rows: measure. Memoization and lighter rows might be enough, and CSS
content-visibility(covered later in this tutorial) may help. - Thousands of rows or more, or heavy rows: virtualization is likely worth its complexity.
The next chapters cover how windowing works and how to build it.
Exercise
A list of 20,000 rows renders slowly on first load. Name two parts of the cost that grow with the row count, and explain why making each row cheaper does not remove the underlying problem.
Show answer
React's render and commit work grows with the row count because it creates a fiber and a DOM node for every row. The browser's style calculation and layout also grow with the number of nodes in the document, and memory use grows too. Making each row cheaper lowers the cost per row, but total cost is rows times cost per row, so the row count is still the multiplier. Only mounting fewer rows, as windowing does, keeps the cost flat as the data grows.
Exercise
Typing in a search box above a 5,000-row list feels laggy, but scrolling the list is smooth. Which measurement would you take first, and what cheaper fix than virtualization might apply?
Show answer
Use the React Profiler or the DevTools Performance panel while typing, to see whether all rows re-render on each keystroke. Smooth scrolling suggests the layout and paint cost is acceptable and the problem is re-rendering. Wrapping the row component in React.memo and keeping its props stable (for example, with stable keys and memoized callbacks) can stop unchanged rows from re-rendering.