Skip to content
Source
Sign inSign up
TanStack/virtual
Open History to see the last commit

virtualizer.md

420 lines14.3 KB

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>)
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.