Capítulo 20 de 20

Chapter 20: Example: Window Virtualization

Core Idea

The window example lets the browser window own scrolling instead of a nested list element. It measures the list's page offset and subtracts scrollMargin from each item transform.

Code Example

const listOffsetRef = React.useRef(0)

React.useLayoutEffect(() => {
  listOffsetRef.current = listRef.current?.offsetTop ?? 0
}, [])

const virtualizer = useWindowVirtualizer({
  count: 10000,
  estimateSize: () => 35,
  overscan: 5,
  scrollMargin: listOffsetRef.current,
})

{virtualizer.getVirtualItems().map((item) => (
  <div
    key={item.key}
    style={{
      position: 'absolute',
      height: `${item.size}px`,
      transform: `translateY(${item.start - virtualizer.options.scrollMargin}px)`,
    }}
  >
    Row {item.index}
  </div>
))}
  • What it demonstrates: Window coordinates and list-local coordinates are reconciled with a measured page offset.

Key Takeaways

  1. Use the window hook when nested overflow is not the desired scroll model.
  2. Keep scrollMargin synchronized with the list's position on the page.
  3. Subtract the margin when translating items.
  4. The inner spacer still uses getTotalSize().

Connects To

  • Ch 003: React exposes both element and window hooks.
  • Ch 011: The dynamic example shows the same window choice with measured rows.