Capítulo 18 de 20

Chapter 18: Example: Smooth Scroll

Core Idea

The smooth-scroll example supplies a custom scrollToFn that interpolates scroll position with an ease-in-out quint curve. Virtualizer methods such as scrollToIndex then use that function.

Code Example

const scrollToFn: VirtualizerOptions<any, any>['scrollToFn'] =
  React.useCallback((offset, canSmooth, instance) => {
    const duration = 1000
    const start = parentRef.current?.scrollTop || 0
    const startTime = (scrollingRef.current = Date.now())

    const run = () => {
      if (scrollingRef.current !== startTime) return
      const elapsed = Date.now() - startTime
      const progress = easeInOutQuint(Math.min(elapsed / duration, 1))
      const interpolated = start + (offset - start) * progress
      parentRef.current?.scrollTo({ top: interpolated })
      if (progress < 1) requestAnimationFrame(run)
    }
    requestAnimationFrame(run)
  }, [])

const rowVirtualizer = useVirtualizer({
  count: 10000,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
  overscan: 5,
  scrollToFn,
})
  • What it demonstrates: Scroll behavior can be replaced while preserving Virtualizer's imperative API.

Key Takeaways

  1. Implement cancellation so a newer scroll supersedes an older animation.
  2. Keep the custom function compatible with the adapter's scrollToFn type.
  3. Use this only when native scrolling behavior is insufficient.

Connects To

  • Ch 007: scrollToFn is an optional Virtualizer hook.
  • Ch 011: Both examples call imperative scroll methods.