### Install and Run Source: https://github.com/tanstack/virtual/blob/main/examples/react/chat/README.md Commands to install dependencies and start the development server for the chat example. ```bash npm install npm run dev ``` -------------------------------- ### Install Solid Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the Solid adapter for TanStack Virtual using npm. ```bash npm install @tanstack/solid-virtual ``` -------------------------------- ### Install Dependencies Source: https://github.com/tanstack/virtual/blob/main/examples/react/pretext/README.md Install project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install Lit Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the Lit adapter for TanStack Virtual using npm. ```bash npm install @tanstack/lit-virtual ``` -------------------------------- ### Install @tanstack/angular-virtual Source: https://github.com/tanstack/virtual/blob/main/packages/angular-virtual/README.md Install the library using your preferred package manager. ```bash npm i @tanstack/angular-virtual ``` ```bash pnpm add @tanstack/angular-virtual ``` ```bash yarn add @tanstack/angular-virtual ``` ```bash bun add @tanstack/angular-virtual ``` -------------------------------- ### Run Pretext Example Source: https://github.com/tanstack/virtual/blob/main/examples/react/pretext/README.md Run the TanStack React Virtual pretext example using pnpm. ```bash pnpm --filter tanstack-react-virtual-example-pretext dev ``` -------------------------------- ### Install Virtual Core Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the framework-agnostic core library for TanStack Virtual using npm. ```bash npm install @tanstack/virtual-core ``` -------------------------------- ### Running the benchmarks Source: https://github.com/tanstack/virtual/blob/main/benchmarks/README.md Commands to install dependencies, build the virtual core, install Playwright browsers, and run the benchmarks with different configurations. ```bash pnpm install pnpm --filter @tanstack/virtual-core build cd benchmarks pnpm exec playwright install chromium # Full matrix, 5 runs per cell (~10 min) pnpm bench # Quick subset pnpm bench -- --runs 2 --libs tanstack,virtua --scenarios mount-fixed-10k # Watch the browser as it runs pnpm bench:headed ``` -------------------------------- ### Install Pretext Source: https://github.com/tanstack/virtual/blob/main/docs/pretext.md Install the Pretext library using npm. This is the first step to integrating text measurement capabilities into your project. ```sh npm install @chenglou/pretext ``` -------------------------------- ### Install Vue Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the Vue adapter for TanStack Virtual using npm. ```bash npm install @tanstack/vue-virtual ``` -------------------------------- ### Install Angular Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the Angular adapter for TanStack Virtual using npm. ```bash npm install @tanstack/angular-virtual ``` -------------------------------- ### Install React Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the React adapter for TanStack Virtual using npm. ```bash npm install @tanstack/react-virtual ``` -------------------------------- ### Install Svelte Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/installation.md Install the Svelte adapter for TanStack Virtual using npm. ```bash npm install @tanstack/svelte-virtual ``` -------------------------------- ### React Virtualizer Example Source: https://github.com/tanstack/virtual/blob/main/docs/introduction.md This example demonstrates how to use TanStack Virtual to virtualize a long list of elements within a scrollable div using React. ```tsx import { useVirtualizer } from '@tanstack/react-virtual'; function App() { // The scrollable element for your list const parentRef = React.useRef(null) // The virtualizer const rowVirtualizer = useVirtualizer({ count: 10000, getScrollElement: () => parentRef.current, estimateSize: () => 35, }) return ( <> {/* The scrollable element for your list */}
{/* The large inner element to hold all of the items */}
{/* Only the visible items in the virtualizer, manually positioned to be in view */} {rowVirtualizer.getVirtualItems().map((virtualItem) => (
Row {virtualItem.index}
))}
) } ``` -------------------------------- ### VirtualItem Start Property Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtual-item.md The starting pixel offset of the item. Typically used for CSS properties like `top`, `left`, or `translateX`/`translateY`. ```typescript start: number ``` -------------------------------- ### Run Angular Development Server Source: https://github.com/tanstack/virtual/blob/main/examples/angular/fixed/README.md Use this command to start the development server. The application will reload automatically when source files are changed. ```bash ng serve ``` -------------------------------- ### Basic Pretext Integration with TanStack Virtual Source: https://github.com/tanstack/virtual/blob/main/docs/pretext.md This example demonstrates how to use Pretext to estimate row heights within a TanStack Virtualizer. It includes caching prepared text, calculating row heights based on content and width, and updating the virtualizer on font loading and resize events. ```tsx import { clearCache, layout, prepare } from '@chenglou/pretext' import { useVirtualizer } from '@tanstack/react-virtual' const font = '14px Arial' const lineHeight = 20 const preparedCache = new Map>() function getPrepared(row: { id: string; text: string }) { const key = `${row.id}:${font}:${row.text}` const cached = preparedCache.get(key) if (cached) { return cached } const prepared = prepare(row.text, font, { whiteSpace: 'pre-wrap', letterSpacing: 0, }) preparedCache.set(key, prepared) return prepared } function estimateRowHeight(row: { id: string; text: string }, contentWidth: number) { const text = layout(getPrepared(row), contentWidth, lineHeight) const textHeight = Math.max(lineHeight, text.height) return textHeight + 24 } function Messages({ rows }: { rows: Array<{ id: string; text: string }> }) { const parentRef = React.useRef(null) const [width, setWidth] = React.useState(640) React.useLayoutEffect(() => { const element = parentRef.current if (!element) { return } const update = () => setWidth(element.clientWidth) const observer = new ResizeObserver(update) update() observer.observe(element) return () => observer.disconnect() }, []) const virtualizer = useVirtualizer({ count: rows.length, getItemKey: (index) => rows[index]!.id, getScrollElement: () => parentRef.current, estimateSize: (index) => estimateRowHeight(rows[index]!, width - 32), }) React.useLayoutEffect(() => { virtualizer.measure() }, [virtualizer, width]) React.useEffect(() => { document.fonts.ready.then(() => { preparedCache.clear() clearCache() virtualizer.measure() }) }, [virtualizer]) return
{/* render virtual rows */}
} ``` -------------------------------- ### Get Angular CLI Help Source: https://github.com/tanstack/virtual/blob/main/examples/angular/fixed/README.md Display help information and command reference for the Angular CLI. Useful for understanding available commands and options. ```bash ng help ``` -------------------------------- ### Stable Key Example Source: https://github.com/tanstack/virtual/blob/main/docs/chat.md Demonstrates the use of stable keys for items in the virtualizer, which is crucial for maintaining scroll position when data is prepended. ```tsx getItemKey: (index) => messages[index]!.id ``` -------------------------------- ### Optional Option: scrollPaddingStart Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Adds pixel padding to the start of the scroll target when scrolling to an element. ```typescript scrollPaddingStart?: number ``` -------------------------------- ### Initialize Window-based Virtualizer with useWindowVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/vue/vue-virtual.md The useWindowVirtualizer hook creates a virtualizer instance specifically configured for the global window object. It simplifies setup by pre-configuring scroll element retrieval for the window. ```typescript function useWindowVirtualizer( options: PartialKeys< VirtualizerOptions, | 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): Virtualizer ``` -------------------------------- ### Get Virtual Items Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns the virtual items for the current state of the virtualizer. ```typescript type getVirtualItems = () => VirtualItem[] ``` -------------------------------- ### Dynamic Measurement in Chat Source: https://github.com/tanstack/virtual/blob/main/docs/chat.md Example of how to handle dynamic message heights in a chat interface using `measureElement` and absolute positioning. ```tsx
``` -------------------------------- ### VirtualItem Object Properties Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtual-item.md The VirtualItem object contains the following properties: key, index, start, end, size, and lane. ```APIDOC ## VirtualItem Object ### Description The `VirtualItem` object represents a single item returned by the virtualizer. It contains information you need to render the item in the coordinate space within your virtualizer's scrollElement and other helpful properties/functions. ### Properties - **key** (string | number | bigint) - The unique key for the item. By default this is the item index, but should be configured via the `getItemKey` Virtualizer option. - **index** (number) - The index of the item. - **start** (number) - The starting pixel offset for the item. This is usually mapped to a css property or transform like `top/left` or `translateX/translateY`. - **end** (number) - The ending pixel offset for the item. This value is not necessary for most layouts, but can be helpful so we've provided it anyway. - **size** (number) - The size of the item. This is usually mapped to a css property like `width/height`. Before an item is measured with the `VirtualItem.measureElement` method, this will be the estimated size returned from your `estimateSize` virtualizer option. After an item is measured (if you choose to measure it at all), this value will be the number returned by your `measureElement` virtualizer option (which by default is configured to measure elements with `getBoundingClientRect()`). - **lane** (number) - The lane index of the item. Items are assigned to the shortest lane. Lane assignments are cached immediately based on the size estimated by `estimateSize` by default; set `laneAssignmentMode: 'measured'` to base assignments on measured sizes instead. In regular lists it will always be set to `0` but becomes useful for masonry layouts. ``` -------------------------------- ### Use 'position' Mode for Direct DOM Updates Source: https://github.com/tanstack/virtual/blob/main/docs/framework/react/react-virtual.md Example configuring `directDomUpdatesMode` to `'position'` to use `top` and `left` CSS properties instead of `transform` for item positioning. ```typescript const virtualizer = useVirtualizer({ count: 10000, getScrollElement: () => parentRef.current, estimateSize: () => 50, directDomUpdates: true, directDomUpdatesMode: 'position', // Use top/left instead of transform }) ``` -------------------------------- ### Get Total Size Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns the total size in pixels for the virtualized items. This measurement will incrementally change if you choose to dynamically measure your elements as they are rendered. ```typescript getTotalSize: () => number ``` -------------------------------- ### anchorTo Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Controls which side of the scrollable content should be treated as the stable anchor when list data changes. Use 'start' for default behavior or 'end' for chat/log feeds. ```APIDOC ## anchorTo ### Description Controls which side of the scrollable content should be treated as the stable anchor when list data changes. The default 'start' preserves TanStack Virtual's existing top/left anchored behavior. Set 'end' for chat, logs, and reverse/inverted feeds. ### Type `'start' | 'end'` ### Default `'start'` ``` -------------------------------- ### resizeItem Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Manually resizes a specific item in the virtualized list. This is useful when an item's size changes dynamically, for example, due to content changes or animations, and you know the new size beforehand. It helps maintain accurate scroll positioning. ```APIDOC ## `resizeItem` ### Description Change the virtualized item's size manually. Use this function to manually set the size calculated for this index. Useful in occations when using some custom morphing transition and you know the morphed item's size beforehand. You can also use this method with a throttled ResizeObserver instead of `Virtualizer.measureElement` to reduce re-rendering. > ⚠️ Please be aware that manually changing the size of an item when using `Virtualizer.measureElement` to monitor that item, will result in unpredictable behaviour as the `Virtualizer.measureElement` is also changing the size. However you can use one of resizeItem or measureElement in the same virtualizer instance but on different item indexes. ### Method `resizeItem(index: number, size: number) => void` ### Parameters #### Path Parameters - **index** (`number`) - The index of the item to resize. - **size** (`number`) - The new size of the item in pixels. ``` -------------------------------- ### Get Current Scroll Offset Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Retrieve the current scroll position in pixels from the start of the scrollable area. ```typescript scrollOffset: number ``` -------------------------------- ### Adding a library Source: https://github.com/tanstack/virtual/blob/main/benchmarks/README.md Instructions on how to add a new library to the benchmarks. ```bash 1. Create `src/pages/MyLibPage.tsx` that registers a `HarnessHandle` (see existing pages for the contract). 2. Wire it into `src/main.tsx`'s switch. 3. Add the library name to `ALL_LIBS` in `runner/run.mjs`. ``` -------------------------------- ### Adding a scenario Source: https://github.com/tanstack/virtual/blob/main/benchmarks/README.md Instructions on how to add a new scenario to the benchmarks. ```bash Add an entry to `SCENARIOS` in `src/scenarios/types.ts`. The runner discovers it automatically. ``` -------------------------------- ### Optional Option: paddingStart Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Adds pixel padding to the beginning of the virtualized area. Useful for spacing. ```typescript paddingStart?: number ``` -------------------------------- ### Get Scroll Element Rect Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Access the current bounding rectangle of the scroll element. ```typescript scrollRect: Rect ``` -------------------------------- ### useWindowVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/vue/vue-virtual.md Initializes a virtualizer instance bound to the browser window object. ```APIDOC ## useWindowVirtualizer ### Description Returns a window-based Virtualizer instance configured to work with the global window object as the scrollElement. ### Method N/A (Vue Hook) ### Parameters #### Request Body - **options** (VirtualizerOptions) - Required - Configuration object for window-based virtualization. ### Request Example const windowVirtualizer = useWindowVirtualizer({ count: 10000, estimateSize: () => 35, }) ### Response #### Success Response - **Virtualizer** (Object) - The virtualizer instance configured for the window scroll context. ``` -------------------------------- ### Get Virtual Indexes Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns the virtual row indexes for the current state of the virtualizer. ```typescript type getVirtualIndexes = () => number[] ``` -------------------------------- ### Benchmark directory structure Source: https://github.com/tanstack/virtual/blob/main/benchmarks/README.md An overview of the directory structure for the virtualization benchmarks, explaining the purpose of key files and directories. ```text benchmarks/ ├── src/ │ ├── main.tsx Reads ?lib=... &scenario=... │ ├── pages/ One file per library; all share the same harness │ ├── lib/ │ │ ├── dataset.ts Deterministic item generator (LCG-seeded) │ │ └── harness.ts Installs window.bench.run() that every page uses │ └── scenarios/types.ts The fixed scenario list. Adding a row here │ surfaces it in every library and the runner. ├── runner/run.mjs Playwright driver. Boots a server, runs each │ (lib × scenario × run), aggregates medians. ├── results/ JSON snapshots + LATEST.md └── package.json ``` -------------------------------- ### Get Scroll Direction Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Indicates the current direction of scrolling ('forward' or 'backward'), or null if not scrolling. ```typescript scrollDirection: 'forward' | 'backward' | null ``` -------------------------------- ### initialMeasurementsCache Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md A previously-captured snapshot of measured item sizes to seed the virtualizer on mount, useful for restoring scroll position. ```APIDOC ## initialMeasurementsCache ### Description A previously-captured snapshot of measured item sizes (from `takeSnapshot()`) to seed the virtualizer with on mount. Useful for restoring scroll position after navigation: persist the result of `takeSnapshot()` (plus the current `scrollOffset`) in your route state, then pass them back as `initialMeasurementsCache` and `initialOffset` to land users at the same position without re-measuring everything from scratch. Items not present in the cache fall back to `estimateSize`; items present have their measured `size` restored. The cache is consumed only once, on the first `getMeasurements()` call after mount. ### Type `Array` ### Default `[]` ``` -------------------------------- ### scrollMargin Option Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Specifies the origin of the scroll offset, useful for headers or multiple virtualizers. Example shows dynamic calculation. ```typescript scrollMargin?: number ``` ```typescript transform: `translateY(${ virtualRow.start - rowVirtualizer.options.scrollMargin }px)` ``` -------------------------------- ### useVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/vue/vue-virtual.md Initializes a virtualizer instance bound to a specific HTML scroll element. ```APIDOC ## useVirtualizer ### Description Returns a standard Virtualizer instance configured to work with an HTML element as the scrollElement. ### Method N/A (Vue Hook) ### Parameters #### Request Body - **options** (VirtualizerOptions) - Required - Configuration object including count, getScrollElement, estimateSize, and other virtualization logic. ### Request Example const rowVirtualizer = useVirtualizer({ count: 10000, getScrollElement: () => parentRef.value, estimateSize: () => 35, }) ### Response #### Success Response - **Virtualizer** (Object) - The virtualizer instance containing methods like getVirtualItems and getTotalSize. ``` -------------------------------- ### Get Distance from End Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns the current pixel distance from the end of the virtualized content. For a vertical list, this is the distance from the bottom. ```typescript getDistanceFromEnd: () => number ``` -------------------------------- ### Create Lit Virtualizer Instance Source: https://github.com/tanstack/virtual/blob/main/docs/framework/lit/lit-virtual.md Initializes a `VirtualizerController` for a scrollable HTML element. This controller manages the virtual scrolling logic and can be accessed within the Lit element's render method to obtain virtual items. ```typescript private virtualizerController = new VirtualizerController( options: PartialKeys< VirtualizerOptions, 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' ) ``` ```typescript render() { const virtualizer = this.virtualizerController.getVirtualizer(); const virtualItems = virtualizer.getVirtualItems(); } ``` -------------------------------- ### Virtualizer Class Constructor Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Initializes a new Virtualizer instance with the provided options. The Virtualizer manages the virtualization logic for scrollable elements, determining which items are visible and their positions. ```APIDOC ## Class: Virtualizer ### Description The `Virtualizer` class is the core of TanStack Virtual. It manages the virtualization logic for scrollable elements, determining which items are visible and their positions. ### Constructor ```typescript constructor(options: VirtualizerOptions) ``` Initializes a new Virtualizer instance with the provided options. ### Options #### Required Options - **`count`** (number) - The total number of items to virtualize. - **`getScrollElement`** (() => TScrollElement) - A function that returns the scrollable element for the virtualizer. It may return `null` if the element is not available yet. - **`estimateSize`** ((index: number) => number) - A function that is passed the index of each item and should return the actual size (or estimated size) for each item. This measurement should return either the width or height depending on the orientation of your virtualizer. #### Optional Options - **`enabled`** (boolean) - Set to `false` to disable scrollElement observers and reset the virtualizer's state. Defaults to `true`. - **`debug`** (boolean) - Set to `true` to enable debug logs. Defaults to `false`. - **`initialRect`** (Rect) - The initial `Rect` of the scrollElement. Useful for SSR environments. Defaults to `undefined`. - **`onChange`** ((instance: Virtualizer, sync: boolean) => void) - A callback function that fires when the virtualizer's internal state changes. The `sync` parameter indicates whether scrolling is currently in progress. - **`overscan`** (number) - The number of items to render above and below the visible area. Defaults to `1`. - **`horizontal`** (boolean) - Set to `true` if your virtualizer is oriented horizontally. Defaults to `false`. - **`paddingStart`** (number) - The padding to apply to the start of the virtualizer in pixels. Defaults to `0`. - **`paddingEnd`** (number) - The padding to apply to the end of the virtualizer in pixels. Defaults to `0`. - **`scrollPaddingStart`** (number) - The padding to apply to the start of the virtualizer in pixels when scrolling to an element. Defaults to `0`. - **`scrollPaddingEnd`** (number) - The padding to apply to the end of the virtualizer in pixels when scrolling to an element. Defaults to `0`. - **`initialOffset`** (number | (() => number)) - The position where the list is scrolled to on render. Defaults to `0`. - **`getItemKey`** ((index: number) => Key) - A function that is passed the index of each item and should return a unique key for that item. Defaults to returning the item's index. - **`rangeExtractor`** ((range: Range) => number[]) - A function that receives visible range indexes and should return an array of indexes to render. Defaults to `defaultRangeExtractor`. ``` -------------------------------- ### Prepend Older Messages Source: https://github.com/tanstack/virtual/blob/main/docs/chat.md Example of prepending older messages to the current message list, which is a common pattern in chat applications. ```tsx setMessages((current) => [...olderMessages, ...current]) ``` -------------------------------- ### InitialMeasurementsCache Option Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md A snapshot of measured item sizes to seed the virtualizer on mount. Useful for restoring scroll position after navigation. ```typescript initialMeasurementsCache: Array ``` -------------------------------- ### WindowVirtualizerController Initialization in Lit Source: https://github.com/tanstack/virtual/blob/main/packages/lit-virtual/README.md Shows how to initialize WindowVirtualizerController for window-based virtualization within a Lit component. This controller manages virtualization based on the browser window's scroll. It requires importing WindowVirtualizerController and is configured with the total item count, estimated item size, and overscan. ```typescript import { WindowVirtualizerController } from '@tanstack/lit-virtual' class MyWindowVirtualElement extends LitElement { private windowVirtualizerController: WindowVirtualizerController constructor() { super() this.windowVirtualizerController = new WindowVirtualizerController(this, { count: this.data.length, estimateSize: () => 350, overscan: 5, }) } // Implement render and other lifecycle methods as needed } ``` -------------------------------- ### createWindowVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/solid/solid-virtual.md Creates a virtualizer instance specifically configured to use the browser window as the scroll container. ```APIDOC ## createWindowVirtualizer ### Description Initializes a virtualizer instance where the scroll container is the browser window. Useful for full-page virtualized lists. ### Method Function Call ### Endpoint createWindowVirtualizer(options) ### Parameters #### Options - **options** (VirtualizerOptions) - Required - Configuration object for window-based virtualization. ### Request Example const virtualizer = createWindowVirtualizer({ count: 1000, estimateSize: () => 50 }); ### Response #### Success Response - **Virtualizer** (Object) - Returns a Virtualizer instance configured for the Window object. ``` -------------------------------- ### scrollOffset Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Represents the current scroll position in pixels from the start of the scrollable area. This value is crucial for maintaining scroll position during state restoration or for programmatic scrolling. ```APIDOC ## `scrollOffset` ### Description This option represents the current scroll position along the scrolling axis. It is measured in pixels from the starting point of the scrollable area. ### Property `scrollOffset: number` ### Returns `number` - The current scroll offset in pixels. ``` -------------------------------- ### Build Angular Project Source: https://github.com/tanstack/virtual/blob/main/examples/angular/fixed/README.md Compile the Angular application into static assets for deployment. The build artifacts are stored in the dist/ directory. ```bash ng build ``` -------------------------------- ### scrollMargin Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Specifies the origin for the scroll offset, representing the space between the scrolling element's beginning and the list's start. Useful for headers or multiple virtualizers. ```APIDOC ## scrollMargin ### Description With this option, you can specify where the scroll offset should originate. Typically, this value represents the space between the beginning of the scrolling element and the start of the list. This is especially useful in common scenarios such as when you have a header preceding a window virtualizer or when multiple virtualizers are utilized within a single scrolling element. ### Type ```typescript scrollMargin?: number ``` ``` -------------------------------- ### takeSnapshot Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns a snapshot of currently measured items. This is useful for saving and restoring the state of the virtualizer, especially across navigation or remounts. It captures the state of rendered items, allowing for accurate restoration of scroll position and item measurements. ```APIDOC ## `takeSnapshot` ### Description Returns a snapshot of currently-measured items as plain `VirtualItem` objects, suitable for round-tripping through state storage and feeding back as `initialMeasurementsCache` on remount. Pair with the current `scrollOffset` to restore exact scroll position after navigation. Only items the consumer has actually rendered (and thus measured) appear in the snapshot; unmeasured items will fall back to `estimateSize` on restore. Returns an empty array if no items have been measured. ### Method `takeSnapshot()` ### Returns `Array` - An array of `VirtualItem` objects representing the measured items. ``` -------------------------------- ### Basic CSS for Virtualization Benchmarks Source: https://github.com/tanstack/virtual/blob/main/benchmarks/index.html CSS styles for the virtualization benchmark page, including body, root element, scroll host, and item elements. ```css html, body, #root { margin: 0; padding: 0; height: 100%; font-family: -apple-system, sans-serif; } .scroll-host { height: 600px; width: 600px; overflow: auto; box-sizing: border-box; } .item { border-bottom: 1px solid #eee; padding: 6px 10px; box-sizing: border-box; } .item.even { background: #fafafa; } ``` -------------------------------- ### VirtualItem Interface Definition Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtual-item.md Defines the structure of a VirtualItem object, which represents a single item in a virtualized list. It includes properties like key, index, start, end, and size. ```typescript export interface VirtualItem { key: string | number | bigint index: number start: number end: number size: number } ``` -------------------------------- ### createVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/solid/solid-virtual.md Creates a virtualizer instance configured to work with a specific HTML element as the scroll container. ```APIDOC ## createVirtualizer ### Description Initializes a virtualizer instance for an HTML element scroll container. It manages the virtual state of items within the specified scrollable area. ### Method Function Call ### Endpoint createVirtualizer(options) ### Parameters #### Options - **options** (VirtualizerOptions) - Required - Configuration object including count, getScrollElement, estimateSize, and optional overrides for rect/offset observation. ### Request Example const virtualizer = createVirtualizer({ count: 1000, getScrollElement: () => parentRef, estimateSize: () => 35 }); ### Response #### Success Response - **Virtualizer** (Object) - Returns a Virtualizer instance containing methods like getVirtualItems() and getTotalSize(). ``` -------------------------------- ### Disable useFlushSync for React 19 Compatibility or Performance Source: https://github.com/tanstack/virtual/blob/main/docs/framework/react/react-virtual.md Example of disabling synchronous updates by setting `useFlushSync` to `false`. This can resolve React 19 warnings or improve performance on lower-end devices. ```typescript const virtualizer = useVirtualizer({ count: 10000, getScrollElement: () => parentRef.current, estimateSize: () => 50, useFlushSync: false, // Disable synchronous updates }) ``` -------------------------------- ### createWindowVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/svelte/svelte-virtual.md Creates a virtualizer instance that uses the browser window as its scroll container. This is suitable for full-page scrolling experiences. ```APIDOC ## `createWindowVirtualizer` ### Description Creates a virtualizer instance that uses the browser window (`window`) as its scroll container. This is optimized for full-page scrolling where the entire viewport is the scrollable area. ### Method Function Call ### Endpoint N/A (Client-side function) ### Parameters #### Function Signature ```typescript function createWindowVirtualizer( options: PartialKeys< VirtualizerOptions, | 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' > ): Virtualizer ``` #### Options Object - `options` (object) - Required - Configuration options for the window virtualizer. Properties like `getScrollElement`, `observeElementRect`, `observeElementOffset`, and `scrollToFn` are managed by default for window scrolling. ### Request Example ```javascript import { createWindowVirtualizer } from '@tanstack/svelte-virtual'; const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`); const itemVirtualizer = createWindowVirtualizer({ count: items.length, estimateSize: () => 40, // Estimate the size of each item }); // Use itemVirtualizer in your Svelte component for window scrolling ``` ### Response #### Success Response - `Virtualizer` (object) - An instance of the Virtualizer, configured for window-based scrolling. ``` -------------------------------- ### Create Virtualizer for Window Source: https://github.com/tanstack/virtual/blob/main/docs/framework/solid/solid-virtual.md The createWindowVirtualizer function initializes a virtualizer instance specifically for the browser window. It simplifies configuration by pre-setting the window as the scroll element. ```tsx function createWindowVirtualizer( options: PartialKeys< VirtualizerOptions, | 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): Virtualizer ``` -------------------------------- ### Create Window Virtualizer Instance Source: https://github.com/tanstack/virtual/blob/main/docs/framework/lit/lit-virtual.md Initializes a `WindowVirtualizerController` for window-based virtual scrolling. This controller is designed to work with the browser window as the scrollable container and abstracts away the need to specify a scroll element. ```typescript private windowVirtualizerController = new WindowVirtualizerController( options: PartialKeys< VirtualizerOptions, 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' ) ``` -------------------------------- ### Virtualizer Instance Properties Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Properties available on the virtualizer instance, providing access to its current options, scroll element, and state. ```APIDOC ## Virtualizer Instance Properties ### `options` #### Description The current options for the virtualizer. This property is updated via your framework adapter and is read-only. #### Type `readonly Required>` ### `scrollElement` #### Description The current scrollElement for the virtualizer. This property is updated via your framework adapter and is read-only. #### Type `readonly TScrollElement | null` ``` -------------------------------- ### followOnAppend Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md When used with anchorTo: 'end', this option controls whether the virtualizer scrolls to the end after new items are appended. It only follows if the viewport was already at the end. ```APIDOC ## followOnAppend ### Description When used with `anchorTo: 'end'`, controls whether the virtualizer scrolls to the end after new items are appended. The follow only happens if the viewport was already at the end before the append; users who have scrolled up to read history are not pulled down. Passing `true` is equivalent to `'auto'`. Passing a scroll behavior uses that behavior for the follow. This option does not follow prepends. ### Type `boolean | 'auto' | 'smooth' | 'instant'` ### Default `false` ``` -------------------------------- ### Capture and Restore Virtualizer State Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Capture the current measurements and scroll offset to save state. Restore the state on remount using `initialMeasurementsCache` and `initialOffset`. ```tsx takeSnapshot: () => Array ``` ```tsx // Capture state on unmount const snapshot = virtualizer.takeSnapshot() const offset = virtualizer.scrollOffset sessionStorage.setItem('myList', JSON.stringify({ snapshot, offset })) // Restore on remount const saved = JSON.parse(sessionStorage.getItem('myList') ?? 'null') useVirtualizer({ count: items.length, estimateSize: () => 50, getScrollElement: () => parentRef.current, initialMeasurementsCache: saved?.snapshot, initialOffset: saved?.offset, }) ``` -------------------------------- ### isAtEnd Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Checks if the viewport is within a specified threshold of the end of the virtualized content. ```APIDOC ## `isAtEnd` ### Description Returns whether the viewport is within `threshold` pixels of the end. If no threshold is provided, `scrollEndThreshold` is used. Use this to decide whether to show "Jump to latest" UI or whether incoming output should be treated as pinned. ### Parameters - **threshold** (number) - Optional - The number of pixels from the end to consider as 'at the end'. Defaults to the virtualizer's `scrollEndThreshold`. ``` -------------------------------- ### Initialize Element-based Virtualizer with useVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/vue/vue-virtual.md The useVirtualizer hook creates a virtualizer instance tied to a specific HTML scroll element. It accepts configuration options for element observation and scrolling behavior. ```typescript function useVirtualizer( options: PartialKeys< VirtualizerOptions, 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): Virtualizer ``` -------------------------------- ### FollowOnAppend Option Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md When used with anchorTo: 'end', controls if the virtualizer scrolls to the end after new items are appended. Follows only if the viewport was already at the end. ```typescript followOnAppend?: boolean | 'auto' | 'smooth' | 'instant' ``` -------------------------------- ### Create Virtualizer for HTML Elements Source: https://github.com/tanstack/virtual/blob/main/docs/framework/solid/solid-virtual.md The createVirtualizer function initializes a virtualizer instance for a specific HTML scroll element. It accepts configuration options and returns a Virtualizer instance to manage virtual scrolling. ```tsx function createVirtualizer( options: PartialKeys< VirtualizerOptions, 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): Virtualizer ``` -------------------------------- ### Virtualizer Options Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md The current options for the virtualizer. This property is updated via your framework adapter and is read-only. ```typescript options: readonly Required> ``` -------------------------------- ### getTotalSize Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Returns the total calculated size in pixels of all virtualized items. ```APIDOC ## `getTotalSize` ### Description Returns the total size in pixels for the virtualized items. This measurement will incrementally change if you choose to dynamically measure your elements as they are rendered. ### Type `() => number` ``` -------------------------------- ### Run Angular Unit Tests Source: https://github.com/tanstack/virtual/blob/main/examples/angular/fixed/README.md Execute unit tests for the Angular application using Karma. This command helps ensure the code functions as expected. ```bash ng test ``` -------------------------------- ### Required Option: count Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Specifies the total number of items that will be virtualized. This is a mandatory option. ```typescript count: number ``` -------------------------------- ### Optional Option: paddingEnd Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Adds pixel padding to the end of the virtualized area. Useful for spacing. ```typescript paddingEnd?: number ``` -------------------------------- ### Virtualizer Class Definition Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md The core Virtualizer class constructor. It takes an options object to configure virtualization. ```typescript export class Virtualizer { constructor(options: VirtualizerOptions) } ``` -------------------------------- ### Optional Option: initialRect Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Provides the initial rectangle of the scroll element. Primarily useful for SSR environments, as it's usually calculated on mount otherwise. ```typescript initialRect?: Rect ``` -------------------------------- ### Inject Window Virtualizer Source: https://github.com/tanstack/virtual/blob/main/packages/angular-virtual/README.md Use `injectWindowVirtualizer` for virtualizers that attach directly to the browser window. This is useful when the scrollable element is the entire viewport. ```typescript import { Component } from '@angular/core' import { injectWindowVirtualizer } from '@tanstack/angular-virtual' @Component({ selector: 'my-window-virtualized-list', template: `
@for (row of virtualizer.getVirtualItems(); track row.index) {
Row {{ row.index }}
}
`, }) export class MyWindowVirtualizedList { virtualizer = injectWindowVirtualizer(() => ({ count: 1000, estimateSize: () => 35, overscan: 5, })) } ``` -------------------------------- ### Optional Option: onChange Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md A callback function executed when the virtualizer's state changes. It receives the virtualizer instance and a sync boolean indicating if scrolling is in progress. ```typescript onChange?: (instance: Virtualizer, sync: boolean) => void ``` -------------------------------- ### Optional Option: initialOffset Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Specifies the initial scroll position. Useful for SSR or conditional rendering scenarios. ```typescript initialOffset?: number | (() => number) ``` -------------------------------- ### VirtualizerController Usage in Lit Source: https://github.com/tanstack/virtual/blob/main/packages/lit-virtual/README.md Demonstrates how to use VirtualizerController to virtualize DOM nodes within a scrollable element in a Lit component. It requires importing LitElement, VirtualizerController, and Ref directives. The controller is initialized with scroll element retrieval, item count, estimated size, and overscan. The render method uses the virtualizer to map items to DOM elements. ```typescript import { LitElement } from 'lit' import { VirtualizerController } from '@tanstack/lit-virtual' import { Ref, createRef } from 'lit/directives/ref.js' class MyVirtualElement extends LitElement { private virtualizerController: VirtualizerController private scrollElementRef: Ref = createRef() constructor() { super() this.virtualizerController = new VirtualizerController(this, { getScrollElement: () => this.scrollElementRef.value, count: 10000, estimateSize: () => 35, overscan: 5, }) } render() { const virtualizer = this.virtualizerController.getVirtualizer() const virtualItems = virtualizer.getVirtualItems() return html`
${virtualItems.map( (item) => html`
${item.index}
`, )}
` } } ``` -------------------------------- ### injectWindowVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/angular/angular-virtual.md This function returns a window-based `AngularVirtualizer` instance configured to work with the window as the scrollElement. ```APIDOC ## `injectWindowVirtualizer` ```ts function injectWindowVirtualizer( options: PartialKeys< VirtualizerOptions, | 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): AngularVirtualizer ``` This function returns a window-based `AngularVirtualizer` instance configured to work with the window as the scrollElement. ``` -------------------------------- ### createVirtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/svelte/svelte-virtual.md Creates a virtualizer instance for a specific scrollable HTML element. This is useful for implementing virtual scrolling within a container element. ```APIDOC ## `createVirtualizer` ### Description Creates a virtualizer instance that uses a provided HTML element as its scroll container. This is ideal for scenarios where you have a specific DOM element that handles scrolling. ### Method Function Call ### Endpoint N/A (Client-side function) ### Parameters #### Function Signature ```typescript function createVirtualizer( options: PartialKeys< VirtualizerOptions, 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' > ): Virtualizer ``` #### Options Object - `options` (object) - Required - Configuration options for the virtualizer. Certain properties like `observeElementRect`, `observeElementOffset`, and `scrollToFn` are automatically handled or can be overridden. ### Request Example ```javascript import { createVirtualizer } from '@tanstack/svelte-virtual'; const rows = Array.from({ length: 1000 }, (_, i) => i); const rowVirtualizer = createVirtualizer({ count: rows.length, getScrollElement: () => document.getElementById('scroll-container'), estimateSize: () => 35, // Estimate the size of each row }); // Use rowVirtualizer in your Svelte component ``` ### Response #### Success Response - `Virtualizer` (object) - An instance of the Virtualizer, providing methods and properties to manage virtual scrolling. ``` -------------------------------- ### Inject Window Virtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/framework/angular/angular-virtual.md Use this function to create a virtualizer instance that targets the browser window as the scrollable element. It exposes adapter-managed state through Angular signals. ```typescript function injectWindowVirtualizer( options: PartialKeys< VirtualizerOptions, | 'getScrollElement' | 'observeElementRect' | 'observeElementOffset' | 'scrollToFn' >, ): AngularVirtualizer ``` -------------------------------- ### scrollToEnd Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Scrolls the virtualizer to the end of the content (bottom for vertical, right for horizontal). ```APIDOC ## `scrollToEnd` ### Description Scrolls the virtualizer to the end of the content. For vertical lists this is the bottom; for horizontal lists this is the right edge. This is useful for "Jump to latest" controls in chat and log views. ### Parameters - **options** (object) - Optional - Configuration for the scroll behavior. - **behavior** ('auto' | 'smooth' | 'instant') - Optional - The scrolling behavior. Defaults to 'auto'. ``` -------------------------------- ### Follow on Append Configuration Source: https://github.com/tanstack/virtual/blob/main/docs/chat.md Configuration option to enable following appended output, ensuring the viewport stays pinned to the end when new messages arrive. ```tsx followOnAppend: true ``` -------------------------------- ### Update Virtualizer Options with Signals Source: https://github.com/tanstack/virtual/blob/main/packages/angular-virtual/README.md Dynamically update virtualizer options by using Angular signals for reactive inputs. This allows the virtualizer to adapt to changes in data or configuration. ```typescript import { Component, input } from '@angular/core' import { injectVirtualizer } from '@tanstack/angular-virtual' @Component({...}) export class MyVirtualizedList { items = input>() virtualizer = injectVirtualizer(() => ({ scrollElement: this.scrollElement(), count: this.items().length, estimateSize: () => 35, overscan: 5, })) } ``` -------------------------------- ### Generate Angular Component Source: https://github.com/tanstack/virtual/blob/main/examples/angular/window/README.md Scaffold new components, directives, pipes, services, classes, guards, interfaces, enums, or modules using the Angular CLI. ```bash ng generate component component-name ``` ```bash ng generate directive|pipe|service|class|guard|interface|enum|module ``` -------------------------------- ### Chat Virtualizer Configuration Source: https://github.com/tanstack/virtual/blob/main/docs/chat.md Configuration for a virtualizer to support chat-like scrolling, including end anchoring and following appended items. ```tsx const virtualizer = useVirtualizer({ count: messages.length, getScrollElement: () => parentRef.current, estimateSize: () => 72, getItemKey: (index) => messages[index]!.id, anchorTo: 'end', followOnAppend: true, scrollEndThreshold: 80, overscan: 6, }) ``` -------------------------------- ### Optional Option: horizontal Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Set to true if the virtualizer should operate in a horizontal orientation. Defaults to false (vertical). ```typescript horizontal?: boolean ``` -------------------------------- ### Measure Virtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Resets any previous item measurements. ```typescript measure: () => void ``` -------------------------------- ### gap Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Sets the spacing in pixels between items in the virtualized list, ensuring consistent visual separation. ```APIDOC ## gap ### Description This option allows you to set the spacing between items in the virtualized list. It's particularly useful for maintaining a consistent visual separation between items without having to manually adjust each item's margin or padding. The value is specified in pixels. ### Type ```typescript gap?: number ``` ``` -------------------------------- ### Measure Element with Virtualizer Source: https://github.com/tanstack/virtual/blob/main/docs/api/virtualizer.md Manually measure a rendered element using the `measureElement` ref callback. Ensure the element has a `data-index` attribute. ```tsx measureElement: (el: TItemElement | null) => void ``` ```tsx
...
```