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

react-virtual.md

147 lines5.7 KB

1---
2title: React Virtual
3---
4​
5The `@tanstack/react-virtual` adapter is a wrapper around the core virtual logic.
6​
7## `useVirtualizer`
8​
9```tsx
10function useVirtualizer<TScrollElement, TItemElement = unknown>(
11 options: PartialKeys<
12 ReactVirtualizerOptions<TScrollElement, TItemElement>,
13 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'
14 >,
15): Virtualizer<TScrollElement, TItemElement>
16```
17​
18This function returns a standard `Virtualizer` instance configured to work with an HTML element as the scrollElement.
19​
20## `useWindowVirtualizer`
21​
22```tsx
23function useWindowVirtualizer<TItemElement = unknown>(
24 options: PartialKeys<
25 ReactVirtualizerOptions<Window, TItemElement>,
26 | 'getScrollElement'
27 | 'observeElementRect'
28 | 'observeElementOffset'
29 | 'scrollToFn'
30 >,
31): Virtualizer<Window, TItemElement>
32```
33​
34This function returns a window-based `Virtualizer` instance configured to work with the window as the scrollElement.
35​
36## React-Specific Options
37​
38### `useFlushSync`
39​
40```tsx
41type ReactVirtualizerOptions<TScrollElement, TItemElement> =
42 VirtualizerOptions<TScrollElement, TItemElement> & {
43 useFlushSync?: boolean
44 }
45```
46​
47Both `useVirtualizer` and `useWindowVirtualizer` accept a `useFlushSync` option that controls whether React's `flushSync` is used for synchronous updates.
48​
49- **Type**: `boolean`
50- **Default**: `true`
51- **Description**: When `true`, the virtualizer will use `flushSync` from `react-dom` to ensure synchronous rendering during scroll events. This provides the most accurate scrolling behavior but may impact performance in some scenarios.
52​
53#### When to disable `useFlushSync`
54​
55You may want to set `useFlushSync: false` in the following scenarios:
56​
57- **React 19 compatibility**: In React 19, you may see the following console warning when scrolling:
58 ```
59 flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.
60 ```
61 Setting `useFlushSync: false` will eliminate this warning by allowing React to batch updates naturally.
62- **Performance optimization**: If you experience performance issues with rapid scrolling on lower-end devices
63- **Testing environments**: When running tests that don't require synchronous DOM updates
64- **Non-critical lists**: When slight visual delays during scrolling are acceptable for better overall performance
65​
66#### Example
67​
68```tsx
69const virtualizer = useVirtualizer({
70 count: 10000,
71 getScrollElement: () => parentRef.current,
72 estimateSize: () => 50,
73 useFlushSync: false, // Disable synchronous updates
74})
75```
76​
77### `directDomUpdates`
78​
79- **Type**: `boolean`
80- **Default**: `false`
81- **Description**: Skip React re-renders for scroll-only updates. When enabled, the virtualizer writes item positions (`top`/`left` or `transform`) and the container size (`height`/`width`) directly to the DOM, and only re-renders when the visible index range or `isScrolling` changes.
82​
83#### Requirements when enabled
84​
85- Item elements must be `position: absolute`; in `'transform'` mode they must also be anchored with `top: 0` / `left: 0`.
86- Item elements must **not** set the main-axis position in their style β€” the virtualizer owns `top` / `left` in `'position'` mode and `transform` in `'transform'` mode.
87- The inner size container must receive `virtualizer.containerRef` and must **not** set `height` / `width` in its style.
88- For multi-lane layouts (grids / masonry), the cross-axis position (e.g. `left: ${(item.lane * 100) / lanes}%`) is stable per item and must still be set in your JSX β€” only the main axis is automated.
89​
90> ⚠️ This flag is intended to be set once at mount. Toggling it (or `directDomUpdatesMode`) at runtime can leave stale inline styles on items and the container.
91​
92> **Note:** If you omit `containerRef`, the virtualizer makes no direct DOM writes β€” it writes neither item positions nor the container size. You're then responsible for positioning items and sizing the container yourself (e.g. in `onChange`), while still benefiting from the skipped re-renders.
93​
94#### Example
95​
96```tsx
97const virtualizer = useVirtualizer({
98 count: 10000,
99 getScrollElement: () => parentRef.current,
100 estimateSize: () => 50,
101 directDomUpdates: true,
102})
103​
104return (
105 <div ref={parentRef} style={{ overflow: 'auto', height: 400 }}>
106 {/* The inner container must use virtualizer.containerRef and not set height */}
107 <div ref={virtualizer.containerRef} style={{ position: 'relative' }}>
108 {virtualizer.getVirtualItems().map((item) => (
109 <div
110 key={item.key}
111 ref={virtualizer.measureElement}
112 data-index={item.index}
113 style={{
114 position: 'absolute',
115 top: 0,
116 left: 0,
117 width: '100%',
118 // Do NOT set top/left/transform β€” the virtualizer handles it
119 }}
120 >
121 Row {item.index}
122 </div>
123 ))}
124 </div>
125 </div>
127```
128​
129### `directDomUpdatesMode`
130​
131- **Type**: `'position' | 'transform'`
132- **Default**: `'transform'`
133- **Description**: Controls how `directDomUpdates` positions item elements.
134 - `'transform'` (default): writes `transform: translate3d(...)`. Promotes items to their own compositor layer β€” usually smoother on long lists, but creates a stacking context and can interfere with `position: fixed` descendants. Item elements must be anchored with `position: absolute`, `top: 0`, and `left: 0`.
135 - `'position'`: writes `top` / `left`. Item elements must be `position: absolute`.
136​
137#### Example
138​
139```tsx
140const virtualizer = useVirtualizer({
141 count: 10000,
142 getScrollElement: () => parentRef.current,
143 estimateSize: () => 50,
144 directDomUpdates: true,
145 directDomUpdatesMode: 'position', // Use top/left instead of transform
146})
147```