Command palette

@yasinsensoy/web

Web · Components

VirtualList

List showing tens of thousands of items without stutter: only the visible items (and a few extra) are in the DOM.

9 exports

Live example

Preview

Person 1
Long note: this row is taller than the others because it has a description that wraps onto two lines.
Person 2
Person 3
Person 4
Person 5
Person 6
Person 7
Person 8
Long note: this row is taller than the others because it has a description that wraps onto two lines.
Person 9
Person 10
Person 11
Person 12
Person 13
Person 14
Person 15
Long note: this row is taller than the others because it has a description that wraps onto two lines.
Person 16
Person 17
Person 18
Person 19

Code

import { VirtualList, PersonRow } from "@yasinsensoy/web";

<VirtualList items={contacts} getKey={(k) => k.id} estimateSize={44}
  className="h-96 rounded-lg border" aria-label="People"
  renderItem={(p) => <PersonRow person={p} />} />

Events

  1. Events appear here when you interact with the preview.

Import

import { VirtualList, useVirtualizer } from "@yasinsensoy/web";

VirtualList

componentClient component

List showing tens of thousands of items without stutter: only the visible items (and a few extra) are in the DOM. Contact lists, records, chats, notifications. For your own layout use the useVirtualizer hook.

  • Item heights can differ; they are measured as they render, and content doesn't jump even if an item above the visible area changes size.
  • With windowScroll it works with the page's own scrolling.
  • Infinite scrolling with onLoadMore + hasMore; "Tekrar dene" on error.
  • Announced to screen readers as a list; each item reports its position within the total (aria-posinset/aria-setsize).
  • The first items are rendered on the server (the first paint isn't empty).
  • While the box scrolls itself the library's overlay scrollbar is used (see ScrollArea); className/style go to the outer box, other props (aria-label, onScroll…) to the element that actually scrolls.
VirtualList({ items, renderItem, getKey, estimateSize, overscan, gap, horizontal, windowScroll, height, empty, onLoadMore, onError, hasMore, loading, threshold, ref, classNames, className, style, ...props }: VirtualListProps<T>): JSX.Element

Examples

<VirtualList items={contacts} getKey={(c) => c.id} estimateSize={56}
  className="h-[480px] rounded-lg border" aria-label="Contacts"
  renderItem={(c) => <ContactRow contact={c} />}
  onLoadMore={nextPage} hasMore={hasMore} empty={<EmptyState preset="search" />} />

const ref = useRef<VirtualListHandle>(null);
ref.current?.scrollToIndex(500, { align: "center", smooth: true });

Virtualization hook showing thousands of items by rendering only the visible ones; the foundation of VirtualList. You can use it directly for your own layout (grid cards, table rows).

  • Item sizes can differ: it starts with an estimate and rendered items are measured with ResizeObserver.
  • When an item above the visible area grows or shrinks, the scroll position is corrected; content doesn't jump.
  • Scrolling is handled in the same frame; it re-renders only when the visible range changes.
useVirtualizer({ count, estimateSize, scrollElement, listElement, overscan, horizontal, gap, paddingStart, paddingEnd, getKey, initialViewport, }: UseVirtualizerOptions): Virtualizer

Examples

const scrollRef = useRef<HTMLDivElement>(null);
const v = useVirtualizer({ count: rows.length, estimateSize: 44, scrollElement: () => scrollRef.current });
<div ref={scrollRef} className="h-96 overflow-auto">
  <div style={{ height: v.totalSize, position: "relative" }}>
    {v.items.map((item) => (
      <div key={item.key} data-index={item.index} ref={v.measureElement}
        style={{ position: "absolute", top: 0, width: "100%", translate: `0 ${item.start}px` }}>
        {rows[item.index].name}
      </div>
    ))}
  </div>
</div>

Options of the useVirtualizer hook.

NameTypeDefaultDescription
countnumberNumber of items.
estimateSizenumber | ((index: number) => number)Estimated size of an item not measured yet (px): a number or a function by index. Real sizes are measured once items render; the closer the estimate, the less the scrollbar jumps.
scrollElement() => HTMLElement | "window" | nullThe scrolled element. If "window", the page itself scrolls (feed, timeline); the list is virtualized from its position on the page.
listElement?() => HTMLElement | nullThe list itself (to find its position on the page in "window" mode). If omitted, the list counts as at the very start of the scrolled element.
overscan?number6Number of extra items drawn before and after the visible area.
horizontal?booleanfalseHorizontal list.
gap?number0Gap between items (px).
paddingStart?number0Padding at the start of the list (px).
paddingEnd?number0Padding at the end of the list (px).
getKey?(index: number) => string | numberindexPersistent key of an item. Measurements are stored by this key; adding items to the start of the list doesn't shift measurements.
initialViewport?number800Default visible area size (px) before the scroll area is measured (on the server, on first render).

VirtualItem

interface

An item to render.

NameTypeDescription
indexnumberIndex of the item.
keystring | numberKey of the item (getKey).
startnumberDistance from the start of the list (px).
sizenumberIts size (px; the estimate if not measured).

Alignment of VirtualList and scrollToIndex.

type VirtualAlign = "start" | "center" | "end" | "auto"

Virtualizer

interface

What the useVirtualizer hook returns.

NameTypeDescription
itemsVirtualItem[]Items that should be rendered now.
totalSizenumberSize of the whole list (px); the inner container's height/width should be this.
measureElement(element: HTMLElement | null) => (() => void) | undefinedFunction to pass to an item's ref to measure it. The item must have a data-index attribute.
scrollToIndex(index: number, options?: { align?: VirtualAlign; smooth?: boolean; }) => voidScrolls to the item. auto: doesn't scroll if already visible.
reset() => voidClears measurements (e.g. when the size of all items changed).

Functions of VirtualList accessed with ref.

NameTypeDescription
scrollToIndex(index: number, options?: { align?: VirtualAlign; smooth?: boolean; }) => voidScrolls to the item. auto: doesn't scroll if already visible.
elementHTMLDivElement | nullThe element that actually scrolls (the list itself in windowScroll mode too).

Classes that can be passed to the inner parts of VirtualList.

NameTypeDescription
content?stringInner container carrying the total size of the items.
item?stringWrapper of each item.
footer?stringLoading/error area at the end of the list.

Props of the VirtualList component.

Extends: Omit<ComponentProps<"div">, "children" | "ref">

NameTypeDefaultDescription
itemsreadonly T[]Items.
renderItem(item: T, index: number) => ReactNodeRenders an item.
getKey?(item: T, index: number) => string | numberindexPersistent key of an item (e.g. (u) => u.id).
estimateSize?number | ((index: number) => number)48Estimated size of an item (px). Items can be of different sizes; they are measured once rendered.
overscan?number6Number of extra items rendered outside the visible area.
gap?number0Gap between items (px).
horizontal?booleanfalseHorizontal list.
windowScroll?booleanfalseThe list scrolls with the page instead of in its own box (feed, timeline). No need to give a height.
height?number | stringHeight of the scroll area (width when horizontal). Can be given with a class too (h-96).
empty?ReactNodeContent shown when the list is empty (e.g. EmptyState).
onLoadMore?() => unknownLoads the next page when nearing the end. See InfiniteScroll.
onError?(error: unknown) => voidCalled when onLoadMore throws; the error is caught and "Tekrar dene" appears.
hasMore?booleanfalseIs there another page to load?
loading?booleanLoading state from outside; while true an indicator shows at the end of the list.
threshold?number400Start loading when this much remains to the end (px).
ref?Ref<VirtualListHandle>Access for scrollToIndex. See VirtualListHandle.
classNames?VirtualListClassNamesClasses added to the inner parts.