Skip to main content

Virtualization

Configure virtual scrolling for long lists, searchable collections, trees, and data tables.

View as Markdown

Virtualization renders the visible rows and a small buffer instead of mounting the entire collection. Every component takes it the same way: create a virtualizer with moraine/virtualizer and pass it to the component’s virtualizer prop.

Virtualizer Components
createListVirtualizer List, Tree, Combobox, MultiSelect, CommandPalette
createTableVirtualizer DataTable

The type argument is the entry type the component renders, such as ComboboxT.Row or DataTableT.Row. The component mounts the visible rows, supplies its scroll container, and scrolls through the virtualizer during keyboard navigation.

Table always renders every row. Use DataTable for long tables. Select also renders every option: a list long enough to need virtualization also needs search, so use Combobox.

When to virtualize#

Start with ordinary rendering. Add virtualization when a long collection makes opening, filtering, or scrolling noticeably slow. It reduces mounted DOM; it does not reduce the cost of loading or filtering the data. Small collections usually do not need it.

Installation#

Install the optional TanStack Virtual dependency alongside Moraine:

List#

Give the list a bounded height and scrolling overflow. Apply context.props to the actual row DOM element: those props carry positioning styles, the measurement ref, and data-index.

import { List } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

type Item = { id: number; label: string }
const items: Item[] = Array.from({ length: 10_000 }, (_, index) => ({
  id: index + 1,
  label: `Result ${index + 1}`,
}))

export function VirtualizedList() {
  const virtualizer = createListVirtualizer<Item>({
    estimateSize: () => 36,
    getItemKey: (item) => item.id,
    overscan: 8,
  })

  return (
    <List
      as="div"
      items={items}
      role="list"
      aria-label="Results"
      class="h-72 overflow-y-auto"
      virtualizer={virtualizer}
      itemRender={(context) => (
        <div {...context.props} role="listitem">
          <div class="flex h-9 items-center px-3">{context.item.label}</div>
        </div>
      )}
    />
  )
}

Keep custom padding and row content inside the positioned row when they could replace its inline styles. See the List examples for fixed and dynamic heights.

Combobox and MultiSelect#

A collection virtualizes rows, not only your input items. Group labels, separators, and options are all virtual rows. Use ComboboxT.Row<ComboboxT.Item<string>> as the virtualizer item type, estimate each row kind, and key each row with row.key.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const items: ComboboxT.Entry<ComboboxT.Item<string>>[] = [
  {
    type: 'group',
    label: 'Projects',
    items: Array.from({ length: 10_000 }, (_, index) => ({
      value: `project-${index}`,
      label: `Project ${index + 1}`,
    })),
  },
]

export function VirtualizedCombobox() {
  const virtualizer = createListVirtualizer<ComboboxT.Row<ComboboxT.Item<string>>>({
    estimateSize: (row) => (row.type === 'label' ? 30 : 36),
    getItemKey: (row) => row.key,
    overscan: 8,
  })

  return (
    <Combobox
      items={items}
      placeholder="Find a project..."
      leading="icon-search"
      openOnControlClick
      classes={{ listbox: 'h-80 max-h-80' }}
      virtualizer={virtualizer}
    />
  )
}

The default collection renderer applies the virtual row props to labels, separators, and options. Custom itemRender content sits inside the option; it does not replace the outer measured row. MultiSelect uses the same row model through MultiSelectT.Row.

CommandPalette flattens group labels and commands into CommandPaletteT.VirtualEntry rows. Key them with entry.key.

DataTable#

Pass a virtualizer from createTableVirtualizer, keyed by row id, and bound the table with maxHeight. DataTable makes its scroll viewport the scroll container and measures the header above the body, so a sticky header does not hide the row that scrollToIndex reveals.

import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createTableVirtualizer } from 'moraine/virtualizer'

type Invoice = { id: number; invoice: string; amount: number }
const invoices: Invoice[] = Array.from({ length: 10_000 }, (_, index) => ({
  id: index + 1,
  invoice: `INV-${index + 1}`,
  amount: index * 25,
}))
const columns: DataTableT.Column<Invoice>[] = [
  { accessorKey: 'invoice', header: 'Invoice' },
  { accessorKey: 'amount', header: 'Amount', meta: { align: 'end' } },
]

export function VirtualizedInvoices() {
  const table = createDataTable({
    data: invoices,
    columns,
    getRowId: (row) => String(row.id),
  })
  const virtualizer = createTableVirtualizer<DataTableT.Row<Invoice>>({
    estimateSize: () => 41,
    getItemKey: (row) => row.id,
    overscan: 8,
  })

  return (
    <DataTable
      table={table}
      virtualizer={virtualizer}
      sticky="header"
      maxHeight={384}
      aria-label="Invoices"
    />
  )
}

getItemKey receives a DataTableT.Row, so row.id is the id from getRowId.

Rows stay in normal table flow: the virtualizer pads the body with two hidden spacer rows instead of positioning rows absolutely, so cells keep native column alignment.

  • estimateSize should be close to the rendered row height for the size variant: about 41 for md. Rows are measured once mounted.
  • Each entry renders one <tr>, so expandedRowRender and paginated are ignored while virtualized, with a development warning. Select-all toggles every row. Tree sub-rows still expand, because each is its own entry.
  • Only a window of rows exists in the DOM, so the table gets aria-rowcount and every rendered row gets aria-rowindex. A value you set yourself is kept.
  • Add the columns option to the virtualizer to also render only the unpinned body cells near the viewport. See DataTable virtualization for the column layout it uses. The table then also gets aria-colcount.
  • virtualizer.scrollToIndex(index) scrolls to a row, and virtualizer.scrollToColumn(index) to a column.

How it works#

The adapter reads the component’s current entries and scroll container, allocates the total scroll size, and positions only the visible rows. Create one virtualizer per list inside a Solid component so its instance and cleanup belong to that component.

estimateSize#

Return a positive estimate in pixels for each row before it is measured. Choose a value close to the expected height; distinguish group labels from options when their sizes differ. Estimates affect the initial scroll range and the accuracy of jumps to unmeasured rows. When the estimate for an item changes, its cached measurement is discarded.

getItemKey#

Return a stable, unique identity. Use an item ID for List and the supplied row.key for collections. The default is the row index; IDs preserve measurements more reliably when rows are reordered or filtered.

overscan#

overscan is the number of extra rows rendered before and after the visible range. It defaults to 1. A modest buffer such as 8 helps scrolling without mounting the whole collection. Increase it only when fast scrolling reveals gaps; larger values increase DOM work.

Other options#

  • gap adds space in pixels between rows.
  • scrollMargin, scrollPaddingStart, and scrollPaddingEnd account for content inside the scroll container that is not a row, such as a sticky header. DataTable measures them when you omit them.
  • rangeExtractor chooses which row indexes to render. Use it to keep a row mounted while it scrolls out of view, as drag and drop does.
  • createListVirtualizer also accepts horizontal to lay rows out side by side. Set isRtl when a horizontal scroll container has dir="rtl".

Dynamic measurements#

Rows are measured automatically through the ref in the virtual row props. Content that wraps or changes size can update its measured height. Do not discard the ref, data-index, or positioning style when adding your own attributes. Avoid competing layout margins and put spacing inside the measured row.

Keyboard navigation#

Options outside the window have no DOM node to scroll into view. Tree, Combobox, MultiSelect, and CommandPalette call virtualizer.scrollToIndex with the entry index of the highlighted or focused item, so keyboard navigation reaches every row without extra wiring.

List and DataTable have no keyboard navigation of their own. Call virtualizer.scrollToIndex(index) directly when your application needs to reveal a row. A call made while the virtual content is mounting runs once it has mounted. instance() exposes the underlying TanStack virtualizer after virtual content mounts; before mounting it is undefined.

Common pitfalls#

  • An unbounded scroll container can render the whole collection. Set a height or max height and scrolling overflow.
  • Applying context.props to an inner label prevents correct row positioning and measurement. Spread them onto the outer row DOM.
  • Using item values as collection row keys ignores group labels. Use the row type and row.key.
  • Sharing one adapter across multiple mounted lists makes its instance ambiguous. Create one per list.
  • Virtualization only mounts a window of rows, so browser find and DOM queries cannot inspect the full dataset. Provide filtering or search for large collections.