Capítulo 17 de 20

Chapter 17: Example: Chat

Core Idea

The React chat example combines end anchoring, stable message IDs, automatic history loading near the top, streaming output, and a latest-position control.

Code Example

const virtualizer = useVirtualizer({
  count: messages.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 74,
  getItemKey: React.useCallback(
    (index: number) => messages[index]!.id,
    [messages],
  ),
  anchorTo: 'end',
  followOnAppend: true,
  scrollEndThreshold: 80,
  overscan: 6,
  directDomUpdates: true,
})

React.useLayoutEffect(() => {
  if (didInitialScroll) return
  virtualizer.scrollToEnd()
  setDidInitialScroll(true)
}, [didInitialScroll, virtualizer])
  • What it demonstrates: A production-shaped reverse feed starts at the latest item and follows output only while pinned.

Key Takeaways

  1. Use IDs, not array indexes, as chat keys.
  2. Let end anchoring compensate for prepended history and growing output.
  3. Use isAtEnd(80) to distinguish latest reading from history reading.
  4. Keep a manual latest action for readers who scroll away.

Connects To

  • Ch 006: The guide defines the reverse-feed contract.
  • Ch 012: Text-heavy chat can use Pretext estimates.