Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/fix-react-19-flushsync.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@tanstack/react-virtual": patch
---

fix: defer flushSync to microtask for React 19 compatibility

React 19 throws a warning when `flushSync` is called from inside a lifecycle method (`useLayoutEffect`). This change wraps the `flushSync` call in `queueMicrotask()` to defer it to a microtask, allowing React to complete its current render cycle before forcing the synchronous update.

Fixes #1094

This fixes the warning: "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering."
2 changes: 1 addition & 1 deletion packages/react-virtual/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function useVirtualizerBase<
...options,
onChange: (instance, sync) => {
if (sync) {
flushSync(rerender)
queueMicrotask(() => flushSync(rerender))
} else {
rerender()
}
Expand Down
5 changes: 4 additions & 1 deletion packages/react-virtual/tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ test('should render given dynamic size', async () => {
expect(renderer).toHaveBeenCalledTimes(3)
})

test('should render given dynamic size after scroll', () => {
test('should render given dynamic size after scroll', async () => {
render(<List itemSize={100} dynamic />)

expect(screen.queryByText('Row 0')).toBeInTheDocument()
Expand All @@ -153,6 +153,9 @@ test('should render given dynamic size after scroll', () => {
target: { scrollTop: 400 },
})

// Wait for microtask to complete (flushSync is deferred via queueMicrotask)
await new Promise<void>((resolve) => queueMicrotask(() => resolve()))

expect(screen.queryByText('Row 2')).not.toBeInTheDocument()
expect(screen.queryByText('Row 3')).toBeInTheDocument()
expect(screen.queryByText('Row 6')).toBeInTheDocument()
Expand Down