Open History to see the last commit
1---
2title: Virtualizer
3---
4β
5The `Virtualizer` class is the core of TanStack Virtual. Virtualizer instances are usually created for you by your framework adapter, but you do receive the virtualizer directly.
6β
7```tsx
8export class Virtualizer<TScrollElement = unknown, TItemElement = unknown> {
9 constructor(options: VirtualizerOptions<TScrollElement, TItemElement>)
10}
11```
12β
13## Required Options
14β
15### `count`
16β
17```tsx
18count: number
19```
20β
21The total number of items to virtualize.
22β
23### `getScrollElement`
24β
25```tsx
26getScrollElement: () => TScrollElement
27```
28β
29A function that returns the scrollable element for the virtualizer. It may return null if the element is not available yet.
30β
31### `estimateSize`
32β
33```tsx
34estimateSize: (index: number) => number
35```
36β
37> π§ If you are dynamically measuring your elements, it's recommended to estimate the largest possible size (width/height, within comfort) of your items. This will ensure features like smooth-scrolling will have a better chance at working correctly.
38β
39This function is passed the index of each item and should return the actual size (or estimated size if you will be dynamically measuring items with `virtualItem.measureElement`) for each item. This measurement should return either the width or height depending on the orientation of your virtualizer.
40β
41## Optional Options
42β
43### `enabled`
44β
45```tsx
46enabled?: boolean
47```
48β
49Set to `false` to disable scrollElement observers and reset the virtualizer's state
50β
51### `debug`
52β
53```tsx
54debug?: boolean
55```
56β
57Set to `true` to enable debug logs
58β
59### `initialRect`
60β
61```tsx
62initialRect?: Rect
63```
64β
65The initial `Rect` of the scrollElement. This is mostly useful if you need to run the virtualizer in an SSR environment, otherwise the initialRect will be calculated on mount by the `observeElementRect` implementation.
66β
67### `onChange`
68β
69```tsx
70onChange?: (instance: Virtualizer<TScrollElement, TItemElement>, sync: boolean) => void
71```
72β
73A callback function that fires when the virtualizer's internal state changes. It's passed the virtualizer instance.
74β
75### `overscan`
76β
77```tsx
78overscan?: number
79```
80β
81The number of items to render above and below the visible area. Increasing this number will increase the amount of time it takes to render the virtualizer, but might decrease the likelihood of seeing slow-rendering blank items at the top and bottom of the virtualizer when scrolling.
82β
83### `horizontal`
84β
85```tsx
86horizontal?: boolean
87```
88β
89Set this to `true` if your virtualizer is oriented horizontally.
90β
91### `paddingStart`
92β
93```tsx
94paddingStart?: number
95```
96β
97The padding to apply to the start of the virtualizer in pixels.
98β
99### `paddingEnd`
100β
101```tsx
102paddingEnd?: number
103```
104β
105The padding to apply to the end of the virtualizer in pixels.
106β
107### `scrollPaddingStart`
108β
109```tsx
110scrollPaddingStart?: number
111```
112β
113The padding to apply to the start of the virtualizer in pixels when scrolling to an element.
114β
115### `scrollPaddingEnd`
116β
117```tsx
118scrollPaddingEnd?: number
119```
120β
121The padding to apply to the end of the virtualizer in pixels when scrolling to an element.
122β
123### `initialOffset`
124β
125```tsx
126initialOffset?: number | (() => number)
127```
128β
129The initial offset to apply to the virtualizer. This is usually only useful if you are rendering the virtualizer in a SSR environment.
130β
131### `getItemKey`
132β
133```tsx
134getItemKey?: (index: number) => Key
135```
136β
137This function is passed the index of each item and should return a unique key for that item. The default functionality of this function is to return the index of the item, but you should override this when possible to return a unique identifier for each item across the entire set. This function should be memoized to prevent unnecessary re-renders.
138β
139### `rangeExtractor`
140β
141```tsx
142rangeExtractor?: (range: Range) => number[]
143```
144β
145This function receives visible range indexes and should return array of indexes to render. This is useful if you need to add or remove items from the virtualizer manually regardless of the visible range, eg. rendering sticky items, headers, footers, etc. The default range extractor implementation will return the visible range indexes and is exported as `defaultRangeExtractor`.
146β
147### `scrollToFn`
148β
149```tsx
150scrollToFn?: (
151 offset: number,
152 options: { adjustments?: number; behavior?: 'auto' | 'smooth' },
153 instance: Virtualizer<TScrollElement, TItemElement>,
154) => void
155```
156β
157An optional function that (if provided) should implement the scrolling behavior for your scrollElement. It will be called with the following arguments:
158β
159- An `offset` (in pixels) to scroll towards.
160- An object indicating whether there was a difference between the estimated size and actual size (`adjustments`) and/or whether scrolling was called with a smooth animation (`behaviour`).
161- The virtualizer instance itself.
162β
163Note that built-in scroll implementations are exported as `elementScroll` and `windowScroll`, which are automatically configured by the framework adapter functions like `useVirtualizer` or `useWindowVirtualizer`.
164β
165> β οΈ Attempting to use smoothScroll with dynamically measured elements will not work.
166β
167### `observeElementRect`
168β
169```tsx
170observeElementRect: (
171 instance: Virtualizer<TScrollElement, TItemElement>,
172 cb: (rect: Rect) => void,
173) => void | (() => void)
174```
175β
176An optional function that if provided is called when the scrollElement changes and should implement the initial measurement and continuous monitoring of the scrollElement's `Rect` (an object with `width` and `height`). It's called with the instance (which also gives you access to the scrollElement via `instance.scrollElement`. Built-in implementations are exported as `observeElementRect` and `observeWindowRect` which are automatically configured for you by your framework adapter's exported functions like `useVirtualizer` or `useWindowVirtualizer`.
177β
178### `observeElementOffset`
179β
180```tsx
181observeElementOffset: (
182 instance: Virtualizer<TScrollElement, TItemElement>,
183 cb: (offset: number) => void,
184 ) => void | (() => void)
185```
186β
187An optional function that if provided is called when the scrollElement changes and should implement the initial measurement and continuous monitoring of the scrollElement's scroll offset (a number). It's called with the instance (which also gives you access to the scrollElement via `instance.scrollElement`. Built-in implementations are exported as `observeElementOffset` and `observeWindowOffset` which are automatically configured for you by your framework adapter's exported functions like `useVirtualizer` or `useWindowVirtualizer`.
188β
189### `measureElement`
190β
191```tsx
192measureElement?: (
193 element: TItemElement,
194 entry: ResizeObserverEntry | undefined,
195 instance: Virtualizer<TScrollElement, TItemElement>,
196) => number
197```
198β
199This optional function is called when the virtualizer needs to dynamically measure the size (width or height) of an item.
200β
201> π§ You can use `instance.options.horizontal` to determine if the width or height of the item should be measured.
202β
203### `scrollMargin`
204β
205```tsx
206scrollMargin?: number
207```
208β
209With 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. If you are using absolute positioning of elements, you should take into account the `scrollMargin` in your CSS transform:
210```tsx
211transform: `translateY(${
212 virtualRow.start - rowVirtualizer.options.scrollMargin
213}px)`
214```
215To dynamically measure value for `scrollMargin` you can use `getBoundingClientRect()` or ResizeObserver. This is helpful in scenarios when items above your virtual list might change their height.
216β
217### `gap`
218β
219```tsx
220gap?: number
221```
222β
223This 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.
224β
225### `lanes`
226β
227```tsx
228lanes: number
229```
230β
231The number of lanes the list is divided into (aka columns for vertical lists and rows for horizontal lists).
232β
233### `isScrollingResetDelay`
234β
235```tsx
236isScrollingResetDelay: number
237```
238β
239This option allows you to specify the duration to wait after the last scroll event before resetting the isScrolling instance property. The default value is 150 milliseconds.
240β
241The implementation of this option is driven by the need for a reliable mechanism to handle scrolling behavior across different browsers. Until all browsers uniformly support the scrollEnd event.
242β
243### `useScrollendEvent`
244β
245```tsx
246useScrollendEvent: boolean
247```
248β
249This option allows you to switch to use debounced fallback to reset the isScrolling instance property after `isScrollingResetDelay` milliseconds. The default value is `true`.
250β
251The implementation of this option is driven by the need for a reliable mechanism to handle scrolling behavior across different browsers. Until all browsers uniformly support the scrollEnd event.
252β
253### `isRtl`
254β
255```tsx
256isRtl: boolean
257```
258β
259Whether to invert horizontal scrolling to support right-to-left language locales.
260β
261### `useAnimationFrameWithResizeObserver`
262β
263```tsx
264useAnimationFrameWithResizeObserver: boolean
265```
266β
267This option enables wrapping ResizeObserver measurements in requestAnimationFrame for smoother updates and reduced layout thrashing. The default value is `false`.
268β
269It helps prevent the "ResizeObserver loop completed with undelivered notifications" error by ensuring that measurements align with the rendering cycle. This can improve performance and reduce UI jitter, especially when resizing elements dynamically. However, since ResizeObserver already runs asynchronously, adding requestAnimationFrame may introduce a slight delay in measurements, which could be noticeable in some cases. If resizing operations are lightweight and do not cause reflows, enabling this option may not provide significant benefits.
270β
271## Virtualizer Instance
272β
273The following properties and methods are available on the virtualizer instance:
274β
275### `options`
276β
277```tsx
278options: readonly Required<VirtualizerOptions<TScrollElement, TItemElement>>
279```
280β
281The current options for the virtualizer. This property is updated via your framework adapter and is read-only.
282β
283### `scrollElement`
284β
285```tsx
286scrollElement: readonly TScrollElement | null
287```
288β
289The current scrollElement for the virtualizer. This property is updated via your framework adapter and is read-only.
290β
291### `getVirtualItems`
292β
293```tsx
294type getVirtualItems = () => VirtualItem[]
295```
296β
297Returns the virtual items for the current state of the virtualizer.
298β
299### `getVirtualIndexes`
300β
301```tsx
302type getVirtualIndexes = () => number[]
303```
304β
305Returns the virtual row indexes for the current state of the virtualizer.
306β
307### `scrollToOffset`
308β
309```tsx
310scrollToOffset: (
311 toOffset: number,
312 options?: {
313 align?: 'start' | 'center' | 'end' | 'auto',
314 behavior?: 'auto' | 'smooth'
315 }
316) => void
317```
318β
319Scrolls the virtualizer to the pixel offset provided. You can optionally pass an alignment mode to anchor the scroll to a specific part of the scrollElement.
320β
321### `scrollToIndex`
322β
323```tsx
324scrollToIndex: (
325 index: number,
326 options?: {
327 align?: 'start' | 'center' | 'end' | 'auto',
328 behavior?: 'auto' | 'smooth'
329 }
330) => void
331```
332β
333Scrolls the virtualizer to the items of the index provided. You can optionally pass an alignment mode to anchor the scroll to a specific part of the scrollElement.
334β
335### `getTotalSize`
336β
337```tsx
338getTotalSize: () => number
339```
340β
341Returns 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.
342β
343### `measure`
344β
345```tsx
346measure: () => void
347```
348β
349Resets any prev item measurements.
350β
351### `measureElement`
352β
353```tsx
354measureElement: (el: TItemElement | null) => void
355```
356β
357Measures the element using your configured `measureElement` virtualizer option. You are responsible for calling this in your virtualizer markup when the component is rendered (eg. using something like React's ref callback prop) also adding `data-index`
358β
359```tsx
360 <div
361 key={virtualRow.key}
362 data-index={virtualRow.index}
363 ref={virtualizer.measureElement}
364 style={...}
365>...</div>
366```
367β
368By default the `measureElement` virtualizer option is configured to measure elements with `getBoundingClientRect()`.
369β
370### `resizeItem`
371β
372```tsx
373resizeItem: (index: number, size: number) => void
374```
375β
376Change 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.
377β
378You can also use this method with a throttled ResizeObserver instead of `Virtualizer.measureElement` to reduce re-rendering.
379β
380> β οΈ 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.
381β
382### `scrollRect`
383β
384```tsx
385scrollRect: Rect
386```
387β
388Current `Rect` of the scroll element.
389β
390### `shouldAdjustScrollPositionOnItemSizeChange`
391β
392```tsx
393shouldAdjustScrollPositionOnItemSizeChange: undefined | ((item: VirtualItem, delta: number, instance: Virtualizer<TScrollElement, TItemElement>) => boolean)
394```
395β
396The shouldAdjustScrollPositionOnItemSizeChange method enables fine-grained control over the adjustment of scroll position when the size of dynamically rendered items differs from the estimated size. When jumping in the middle of the list and scrolling backward new elements may have a different size than the initially estimated size. This discrepancy can cause subsequent items to shift, potentially disrupting the user's scrolling experience, particularly when navigating backward through the list.
397β
398### `isScrolling`
399β
400```tsx
401isScrolling: boolean
402```
403β
404Boolean flag indicating if list is currently being scrolled.
405β
406### `scrollDirection`
407β
408```tsx
409scrollDirection: 'forward' | 'backward' | null
410```
411β
412This option indicates the direction of scrolling, with possible values being 'forward' for scrolling downwards and 'backward' for scrolling upwards. The value is set to null when there is no active scrolling.
413β
414### `scrollOffset`
415β
416```tsx
417scrollOffset: number
418```
419β
420This option represents the current scroll position along the scrolling axis. It is measured in pixels from the starting point of the scrollable area.