Sub topic 3
Variable-Height Virtual Lists in React
This chapter assumes you know React function components, hooks, CSS position and overflow, and browser scroll events. Fixed-height rows are simple because an index maps directly to an offset. Variable-height rows need measurement.
Measure rows as they render
A virtualization library starts with an estimated height. After each row renders, it measures the real height and recalculates later offsets. TanStack Virtual uses estimateSize and measureElement for this:
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function MessageList({ messages }: { messages: string[] }) {
const scrollRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: messages.length,
getScrollElement: () => scrollRef.current,
estimateSize: () => 48,
measureElement: (element) => element.getBoundingClientRect().height,
overscan: 4,
});
return (
<div ref={scrollRef} 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, width: "100%",
transform: `translateY(${item.start}px)` }}
>
{messages[item.index]}
</div>
))}
</div>
</div>
);
}Images, fonts, and expanding content can change a row after its first measurement. Ensure those changes trigger a remeasurement.
Keys, state, and memoization
Use a stable item identifier for key, not the visible index when items can be inserted or removed. Virtualization reuses a small number of mounted rows, so index keys can attach input state to the wrong item. Keep persistent state in the data model or a parent component. Memoize expensive row components only after profiling.
Scrolling and restoring position
Use the virtualizer's scrollToIndex(index) method for programmatic navigation. Save scrollTop when leaving a view and restore it after the scroll container and item data exist. With measured rows, scrolling to an unrendered index may begin from an estimate and adjust after measurement.
Accessibility and find-in-page
Expose the list's semantic role and useful counts, such as aria-rowcount. Give each rendered row a stable label and preserve keyboard focus when rows mount and unmount. Browser find-in-page cannot search text that virtualization has removed from the DOM. Offer filtering, search results, or a non-virtualized detail view when users must search all content.
Infinite loading
When the last virtual item approaches items.length - 1, request the next page. Guard the request with a loading flag, append results immutably, and increase count only for known items. Display loading and error rows inside the virtual list.
Grids and horizontal virtualization
For a grid, virtualize rows and columns, then position each cell from both indexes. Horizontal lists use the same model with scrollLeft, widths, and horizontal offsets. Choose a library that supports lanes or multiple virtualizers if both axes are large.
When not to virtualize
Pagination is often simpler when users need stable URLs, accessible search, or predictable browser find-in-page. For moderately long lists, CSS can reduce off-screen rendering without removing nodes:
.row {
content-visibility: auto;
contain-intrinsic-size: auto 48px;
}Exercise
Why should a variable-height virtual list use stable item keys?
Show answer
Stable keys keep component state attached to the same data item when rows are reused or items move.