Capítulo 16 de 20

Chapter 16: Example: Infinite Scroll

Core Idea

The infinite-scroll example reserves one loader row while another page exists. It watches the last virtual item and requests the next page only when the loader enters the rendered range.

Code Example

const rowVirtualizer = useVirtualizer({
  count: hasNextPage ? allRows.length + 1 : allRows.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 100,
  overscan: 5,
})

React.useEffect(() => {
  const [lastItem] = [...rowVirtualizer.getVirtualItems()].reverse()
  if (
    lastItem?.index >= allRows.length - 1 &&
    hasNextPage &&
    !isFetchingNextPage
  ) {
    fetchNextPage()
  }
}, [
  hasNextPage,
  fetchNextPage,
  allRows.length,
  isFetchingNextPage,
  rowVirtualizer.getVirtualItems(),
])
  • What it demonstrates: A virtual loader sentinel triggers paginated fetching near the end.

Key Takeaways

  1. Add the loader index only while another page can be fetched.
  2. Guard fetches with isFetchingNextPage.
  3. Keep query state and error handling outside the virtualizer.
  4. Render a loading message for the sentinel row.

Connects To

  • Ch 007: `count) controls whether the sentinel exists.
  • Ch 011: Both patterns use a useful estimate and virtual item range.