From 5cb65244dc561b3dd95ffa10689be5b423d4b9c9 Mon Sep 17 00:00:00 2001 From: Rohan Kulkarni Date: Mon, 17 Aug 2026 04:55:47 -0700 Subject: [PATCH] Fix maintainVisibleContentPosition with rapid data updates (#53542) (#57955) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Fixes https://github.com/react/react-native/issues/53542 **Problem:** `maintainVisibleContentPosition` fails when FlatList data is updated rapidly with prepends in quick succession (e.g., chat receiving messages). After 2 prepends before native scroll drains, render window stays frozen, `onViewableItemsChanged` suppressed, `onEndReached` never fires. **Root cause:** `pendingScrollUpdateCount` assumption is structurally unsound – it increments by 1 per prepend in `getDerivedStateFromProps` (0→1→2) but native scroll events are dispatched as unique events that coalesce. Verified in C++: - `ScrollViewEventEmitter.cpp:13` – `onScroll` dispatched with `dispatchUniqueEvent("scroll", ...)` - `EventQueue.cpp:29-50` – unique event whose target+type matches existing replaces in place (line 49) instead of appending So N scroll events emitted before queue flush deliver exactly 1 to JS. Single coalesced event drains 2→1 leaving blocked. Also leak when JS predicate fires (old key found at new index) but native declines to adjust (tag recycled, view deleted, delta ≤0.5, clamped). **Fix (1 file, 2 lines core):** Clamp pending to at most 1 and drain to 0 on any scroll: - `pendingScrollUpdateCount: 1` instead of `prev+1` – prevents accumulation during rapid prepends - `setState({pendingScrollUpdateCount: 0})` instead of `-1` – single coalesced scroll unblocks This turns "stuck at N" into unblocked after next scroll, fixing frozen window / viewability / onEndReached for rapid updates. For leak path where native declines (no scroll ever), flag would still be stranded at 1 – addressed by boolean rename + escape hatch in follow-up, but this PR already strictly improves and matches existing tests that drain 0→1→0. ## Changelog: [GENERAL] [FIXED] - Fix maintainVisibleContentPosition with rapid data updates (https://github.com/react/react-native/issues/53542) Pull Request resolved: https://github.com/react/react-native/pull/57955 Test Plan: **Jest (VirtualizedList):** ```bash yarn jest --watchman=false packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js --no-coverage --ci # Before: new coalesced test fails with pending 1 # After: 83 passed (82 existing + 1 new rapid prepends with coalesced scroll), 1 skipped, 59 snapshots ``` **New test ( regression for https://github.com/react/react-native/issues/53542 ):** - Simulates 2 rapid prepends WITHOUT intermediate scroll (5 + 3 items) - Only 1 coalesced scroll event (delta 8*ITEM_HEIGHT) - Asserts `pendingScrollUpdateCount === 0` (fails on main with 1) and `firstVisibleItemKey` not null **Existing MVCP tests still pass:** - `handles maintainVisibleContentPosition` - `handles multiple rapid prepends` (separate scroll per prepend) - `delta stays bounded` - `minIndexForVisible >0` and `inverted` **Lint:** ```bash yarn lint # Done (max-warnings 0) ``` Closes https://github.com/react/react-native/issues/53542 Reviewed By: javache Differential Revision: D115907610 Pulled By: fabriziocucci fbshipit-source-id: 0cd59b35d7c43803a000b93779cd84c9c4202053 --- .../Lists/VirtualizedList.js | 6 +- .../Lists/__tests__/VirtualizedList-test.js | 77 +++++++++++++++++++ 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/packages/virtualized-lists/Lists/VirtualizedList.js b/packages/virtualized-lists/Lists/VirtualizedList.js index a8593403e4c..8545ba4c6ff 100644 --- a/packages/virtualized-lists/Lists/VirtualizedList.js +++ b/packages/virtualized-lists/Lists/VirtualizedList.js @@ -777,7 +777,7 @@ class VirtualizedList extends StateSafePureComponent< firstVisibleItemKey: newFirstVisibleItemKey, pendingScrollUpdateCount: maintainVisibleContentPositionAdjustment != null - ? prevState.pendingScrollUpdateCount + 1 + ? 1 : prevState.pendingScrollUpdateCount, }; } @@ -1760,9 +1760,7 @@ class VirtualizedList extends StateSafePureComponent< zoomScale, }; if (this.state.pendingScrollUpdateCount > 0) { - this.setState<'pendingScrollUpdateCount'>(state => ({ - pendingScrollUpdateCount: state.pendingScrollUpdateCount - 1, - })); + this.setState<'pendingScrollUpdateCount'>({pendingScrollUpdateCount: 0}); } this._updateViewableItems(this.props, this.state.cellsAroundViewport); if (!this.props) { diff --git a/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js b/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js index 6547145e920..661be1b1f83 100644 --- a/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js +++ b/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js @@ -2877,6 +2877,83 @@ it('maintainVisibleContentPosition with inverted VirtualizedList handles prepend expect(anchorAfterPrepend).toBeLessThanOrEqual(anchorBeforePrepend + 10); }); +it('handles rapid prepends with coalesced scroll event (regression for #53542)', async () => { + const items = generateItems(20); + const ITEM_HEIGHT = 10; + + let component; + await act(() => { + component = create( + , + ); + }); + + await act(() => { + simulateLayout(component, { + viewport: {width: 10, height: 50}, + content: {width: 10, height: items.length * ITEM_HEIGHT}, + }); + simulateScroll(component, {x: 0, y: 50}); + performAllBatches(); + }); + + const afterFirstPrepend = [...generateItems(5, items.length), ...items]; + const afterSecondPrepend = [ + ...generateItems(3, afterFirstPrepend.length), + ...afterFirstPrepend, + ]; + + // Two rapid prepends WITHOUT intermediate scroll (coalesced native event) + await act(() => { + component.update( + , + ); + }); + + await act(() => { + component.update( + , + ); + }); + + // Only ONE coalesced scroll event for both prepends (delta 8*ITEM_HEIGHT) + // This simulates EventQueue coalescing: dispatchUniqueEvent replaces previous scroll + // Previously: pending 0→1→2, scroll 2→1 (still blocked). Now: 0→1→1→0 (unblocked) + await act(() => { + simulateContentLayout(component, { + width: 10, + height: afterSecondPrepend.length * ITEM_HEIGHT, + }); + simulateScroll(component, {x: 0, y: 50 + 8 * ITEM_HEIGHT}); + performAllBatches(); + }); + + // Pending should be 0, not 1 – this fails on main before fix + expect(component.getInstance().state.pendingScrollUpdateCount).toBe(0); + expect(component.getInstance().state.firstVisibleItemKey).not.toBeNull(); + expect( + component.getInstance().state.cellsAroundViewport.first, + ).toBeGreaterThanOrEqual(0); +}); + function generateItems(count, startKey = 0) { return Array(count) .fill()