Trivia Questions2 min readPremium

Virtualizing Variable-Height Lists

Fixed-height virtualization is simple arithmetic. Real feeds (chat messages, social posts, comments) have rows whose heights depend on content, so you cannot compute positions with index * rowHeight. Here is how production virtualizers handle it. Virtualizing variable-height lists is exactly what libraries like TanStack Virtual do under the hood.

1. Estimate, then measure

  1. Start with an estimated height for every row (for example, 80px) so the total height and scrollbar are roughly right.
  2. When a row renders, measure its real height (via a ref and getBoundingClientRect, or a ResizeObserver to catch later changes such as images loading).
  3. Store measured heights in a cache keyed by item id.

2. Offsets via prefix sums

Each row’s top position is the sum of heights of all rows before it.

offset[0] = 0
offset[i] = offset[i - 1] + height(i - 1)   // measured or estimated

To find the first visible row for a given scrollTop, binary search the offsets array, which takes O(log n) instead of scanning every row.

3. Scroll anchoring

When a row above the viewport gets measured and turns out taller than estimated, every row below shifts down and the content the user is reading jumps. Fixes:

  • Adjust scrollTop by the height delta of rows measured above the viewport.
  • Rely on the browser’s CSS overflow-anchor where the layout allows it.

4. Reverse lists (chat)

Chat UIs start at the bottom and load older messages when scrolling up. Prepending items changes every index, so key rows by stable id, not index, and preserve the distance from the bottom when older pages are inserted.

5. Infinite loading

Combine virtualization with pagination: when the rendered range gets within N rows of the end, fetch the next page. Show placeholder rows (skeletons) with estimated heights while loading.

6. Pitfalls

  • Measuring every frame causes layout thrashing. Measure once per row (and on resize), then cache.
  • Index keys mix up cached heights when the list is reordered or prepended. Use ids.
  • Images without dimensions change height after load. Reserve space with width/height or aspect-ratio.

Virtualizing Variable-Height Lists: Interview Summary

Estimate heights, measure on render, cache by id, compute offsets with prefix sums, find the visible range with binary search, and correct scroll position when rows above the viewport change size.