Capítulo 7 de 20

Chapter 7: Virtualizer

Core Idea

Virtualizer is the core class behind the framework adapters. Its options define the data count, scroll source, estimates, range extraction, spacing, measurement, anchoring, and scroll behavior; its methods expose virtual items, geometry, and imperative control.

Key Concepts

  • Required options: count, getScrollElement, and estimateSize establish the collection and its axis geometry.
  • Scroll source: getScrollElement may return null before mount; a window adapter uses the browser window.
  • Measurement: measureElement observes rendered DOM size; resizeItem accepts a known size.
  • Range: getVirtualItems() returns records for rendering; getVirtualIndexes() returns indexes.
  • Spacing: paddingStart, paddingEnd, gap, and scroll padding affect geometry and scroll alignment.
  • Axes: horizontal changes the measured axis; lanes creates parallel lanes.
  • Identity: getItemKey provides stable keys; rangeExtractor customizes returned indexes.
  • Imperative scroll: scrollToOffset, scrollToIndex, scrollBy, and scrollToEnd control position.
  • State: scrollOffset, scrollDirection, isScrolling, and scrollRect expose current state.
  • Anchoring: anchorTo, followOnAppend, scrollEndThreshold, getDistanceFromEnd, and isAtEnd support reverse feeds.
  • Recalculation: measure() recalculates measurements after geometry changes; takeSnapshot() supports state capture.
  • Update hook: onChange(instance, sync) runs when the virtualizer changes and can support direct DOM updates.
  • Options: overscan trades render work for scroll continuity; enabled can disable observers and reset state.

Code Examples

const virtualizer = useVirtualizer({
  count: items.length,
  getScrollElement: () => parentRef.current,
  estimateSize: (index) => items[index].size,
  getItemKey: (index) => items[index].id,
  overscan: 5,
})

const items = virtualizer.getVirtualItems()
virtualizer.scrollToIndex(40)
  • What it demonstrates: A stable-key, data-driven virtualizer plus range inspection and imperative navigation.

Key Takeaways

  1. Choose the scroll source and axis before tuning estimates.
  2. Keep one measurement owner per item index.
  3. Treat estimateSize as geometry input, not merely a placeholder.
  4. Use spacing options for virtual geometry and scroll padding for alignment.
  5. Customize lower-level callbacks only when the default range and scroll behavior are insufficient.

Connects To

  • Ch 008: VirtualItem contains the geometry consumed by rendering.
  • Ch 015: Sticky items use rangeExtractor.
  • Ch 018: Custom smooth motion uses scrollToFn.