Capítulo 3 de 20

Chapter 3: React Virtual

Core Idea

The React adapter exposes useVirtualizer for an element scroll container and useWindowVirtualizer for the browser window. Both return a Virtualizer instance whose items are rendered by ordinary React JSX.

Key Concepts

  • useVirtualizer: Creates a virtualizer driven by getScrollElement.
  • useWindowVirtualizer: Creates a virtualizer driven by window scrolling.
  • React ref: The scroll element is commonly held in useRef and returned from getScrollElement.
  • getVirtualItems(): Supplies the current items to map in JSX.
  • useFlushSync: Controls whether scroll updates use synchronous React flushing.
  • directDomUpdates: Allows direct DOM positioning for high-frequency scrolling when requirements are met.
  • directDomUpdatesMode: Selects the direct-update behavior described by the adapter.
  • Lifecycle: The virtualizer's lifecycle should match the scroll element's lifecycle.

Code Examples

const parentRef = React.useRef<HTMLDivElement>(null)

const rowVirtualizer = useVirtualizer({
  count: 10000,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
})

return (
  <div ref={parentRef} style={{ height: 400, overflow: 'auto' }}>
    <div style={{ height: `${rowVirtualizer.getTotalSize()}px`, position: 'relative' }}>
      {rowVirtualizer.getVirtualItems().map((virtualRow) => (
        <div
          key={virtualRow.key}
          style={{
            position: 'absolute',
            transform: `translateY(${virtualRow.start}px)`,
            height: `${virtualRow.size}px`,
            width: '100%',
          }}
        >
          Row {virtualRow.index}
        </div>
      ))}
    </div>
  </div>
)
  • What it demonstrates: The React hook, a bounded scroll viewport, a full-size spacer, and virtual item rendering.

Key Takeaways

  1. Use useWindowVirtualizer only when the window owns scrolling.
  2. Keep the virtualizer attached to the same scroll element for its lifetime.
  3. React-specific update options should be enabled only after measuring their effect.
  4. The adapter returns the core API; it does not replace your list markup.

Connects To

  • Ch 007: Options and methods come from Virtualizer.
  • Ch 011: Dynamic React rows use the measurement ref.
  • Ch 020: Window mode adds page-offset handling.