Sub topic 1
Why Long Lists Get Slow
Prerequisites
This chapter assumes you know React function components, props, state, useRef, and useEffect. You should also understand basic CSS positioning, overflow scrolling, and browser scroll events.
Why long lists get slow
A list with 20,000 rows creates 20,000 DOM elements if every row renders at once. The browser must calculate styles, lay out elements, paint pixels, and sometimes update accessibility information for all of them. React must also reconcile a large component tree when the list or one of its rows changes.
Most of those rows are below the viewport. Their work does not help the learner see the current screen. Long rows with images, event handlers, and nested components make the cost higher.
The problem is not only the first render. Scrolling can trigger layout and paint work, while filtering or updating one item can cause many rows to be checked again.
Measure before you optimize
Use the React Profiler to inspect component render times. Use the browser Performance panel to record initial rendering and scrolling. Check:
- Time until the first useful screen appears.
- Number of DOM nodes.
- Long tasks during scrolling.
- Frames per second while rapidly scrolling.
- Memory usage.
Compare the same interaction before and after a change. Virtualization helps when rendering fewer rows reduces these costs. It adds complexity, so do not assume it is needed for every list.
The windowing idea: render only what is visible
Windowing, also called virtualization, renders a small window around the viewport instead of the entire collection. As the user scrolls, the application removes rows leaving the window and adds rows entering it.
The list still needs to feel full. A spacer element represents the total height of every row, while the visible rows are positioned at their real offsets.
The scroll container, the spacer, and positioned rows
A fixed-height list usually has three layers:
- Scroll container: a fixed-height element with
overflow: auto. - Spacer: an inner element whose height equals
rowCount * rowHeight. - Rows: visible children positioned absolutely inside the spacer.
For row index i, its vertical offset is i * rowHeight. If the scroll position is scrollTop, the first visible index is approximately floor(scrollTop / rowHeight). The last index uses the viewport height in the same calculation.
Render a few extra rows before and after this range. This overscan hides blank gaps when scrolling quickly. Variable-height rows require measurement because an index no longer maps to an offset with one multiplication.
Exercise
Why does a virtualized list need a spacer element?
Show answer
The spacer preserves the full scrollable height, so the scrollbar represents all items even though only nearby rows are mounted.