Capítulo 12 de 20

Chapter 12: Example: Pretext Measurement

Core Idea

This React example uses Pretext to estimate text-heavy message heights before DOM measurement. It recalculates width-dependent layout on resize, clears caches after fonts load, and keeps TanStack Virtual responsible for scrolling and range extraction.

Code Example

const rowVirtualizer = useVirtualizer({
  count: messages.length,
  estimateSize: React.useCallback(
    (index) => estimateMessageHeight(messages[index]!, viewportWidth),
    [fontVersion, viewportWidth],
  ),
  getItemKey: React.useCallback((index) => messages[index]!.id, []),
  getScrollElement: () => parentRef.current,
})

{rowVirtualizer.getVirtualItems().map((virtualRow) => (
  <div
    key={virtualRow.key}
    style={{
      height: `${virtualRow.size}px`,
      transform: `translateY(${virtualRow.start}px)`,
    }}
  >
    <article className="message-bubble">...</article>
  </div>
))}
  • What it demonstrates: Text measurement is supplied as an estimate while virtual rendering remains unchanged.

Key Takeaways

  1. Cache prepare() by text and typography inputs.
  2. Rerun layout() when viewport width changes.
  3. Clear Pretext caches and recalculate after fonts are ready.
  4. Use DOM measurement or resizeItem for non-text content.

Connects To

  • Ch 005: The guide explains Pretext's boundaries.
  • Ch 017: Chat uses stable message identity and dynamic row behavior.