Repository navigation
fix: avoid re-rendering unchanged Table rows and cells - #10816
pete-woods wants to merge 1 commit into
Conversation
56133fd to
ebcd3b2
Compare
ebcd3b2 to
e9ad1b5
Compare
|
In your own words, how is this different from #10768? |
To be completely honest I didn't spot that PR. I set "the machine" on this performance tuning task before I realised others had the same issue. I'll have a look through to see how the implementations compare. |
|
So the fix here is more general. But both changes I think make sense combined:
With the two PRs combined I think we'd see even fewer re-renders. |
|
Getting opus to compare the performance of each. I'm also gonna look how the numbers compare if we combined both. Edit: Below is Opus's analysis, which seems to confirm what I expected (they combine well). Table render cost:
|
| Scenario | main |
#10768 | #10816 | Combined |
|---|---|---|---|---|
| Container resized (its own width state, #10759) | 20 / 40 | 0 / 0 | 0 / 0 | 0 / 0 |
| Parent re-renders with a new width | 40 / 80 | 40 / 80 | 0 / 0 | 0 / 0 |
| Parent re-renders, nothing changed | 40 / 80 | 40 / 80 | 0 / 0 | 0 / 0 |
| Click a cell (#10477) | 42 / 84 | 42 / 84 | 23 / 41 | 23 / 41 |
| Arrow key to next row (#10477) | 23 / 45 | 23 / 45 | 4 / 8 | 4 / 8 |
| Change one row's data | 40 / 80 | 40 / 80 | 1 / 2 | 1 / 2 |
| Tree: expand one row | 100 / 100 | 100 / 100 | 5 / 5 | 5 / 5 |
| Tree: add a child row | 101 / 101 | 101 / 101 | 6 / 6 | 6 / 6 |
Setup:
- Flat table: 20 rows, 2 columns,
selectionMode="multiple", inside aResizableTableContainer. - Tree table: 10 parents with 4 children each, 9 of the parents expanded.
- Counting: each
RowandCellcounts a render whenever itsclassNamerender prop runs. - Environment: Jest with jsdom and the repo's test setup. That setup uses StrictMode, so some counts include double renders.
- Container resize:
clientWidthis mocked and a windowresizeevent is fired, the same way Fix/table state identity #10768's tests do it. - "Click a cell" on fix: avoid re-rendering unchanged Table rows and cells #10816: the first selection flips
isEmpty, which re-renders every row. A later click renders about 2 rows.
Source: /tmp/CompareRenders.test.js.
Tree table timings (Chromium)
From Treeble.perf.browser.test.tsx: 50 parents with 5 children each, 3 columns, selectionMode="multiple", dev build, timed with flushSync. Each cell gives the median over 5–7 rounds in two separate runs, as "run 1 / run 2".
| Scenario | main |
#10768 | #10816 | Combined | Rows rendered (main → #10816) |
|---|---|---|---|---|---|
| Add 1 child row | 473 / 501 ms | 465 / 488 ms | 32 / 30 ms | 29 / 29 ms | 613 → 13 |
| Parent re-renders, nothing changed | 146 / 159 ms | 126 / 145 ms | 30 / 12 ms | 12 / 13 ms | 614 → 0 |
| Add 60 child rows | 294 / 247 ms | 262 / 243 ms | 82 / 95 ms | 98 / 100 ms | 1154 → 306 |
| Expand one row | 144 / 142 ms | 138 / 149 ms | 15 / 13 ms | 13 / 12 ms | 600 → 6 |
| Collapse one row | 226 / 143 ms | 138 / 141 ms | 13 / 12 ms | 11 / 12 ms | 590 → 1 |
#10768 renders the same rows as main in this benchmark, and combined renders the same rows as #10816.
Container resize timings (Chromium)
A ResizableTableContainer with 300 rows and 4 columns. Each round changes the container's width through the DOM, so the real ResizeObserver fires. The figures are total React render time per resize from <Profiler> actualDuration, as the median of 9 resizes in each of two runs.
| Version | Render time per resize | Cells rendered per resize |
|---|---|---|
main |
47.9 / 49.5 ms | 1,200 |
| #10768 | 0.7 / 1.1 ms | 0 |
| #10816 | 4.5 / 4.9 ms | 0 |
| Combined | 0.9 / 0.7 ms | 0 |
#10816 renders no cells here, but it still runs each row and cell's wrapper to compare render keys, which costs about 4 ms for 300 rows. #10768 avoids that because TableStateContext keeps its identity.
Source: /tmp/ResizeBench.browser.test.tsx.
Takeaways
- Fix/table state identity #10768 only helps when the table state really doesn't change. That's the container resizing itself, which is Table: TableStateContext changes identity every render, so ResizableTableContainer re-renders every cell on width changes #10759's exact case. A parent re-render rebuilds the collection from inline
<Column>elements, so the state is new and every row renders. So does any real change to focus, selection, data or expansion. - fix: avoid re-rendering unchanged Table rows and cells #10816 helps for every kind of update, because rows and cells skip rendering even when the state changes. What's left is the per-row render-key check, about 4 ms for 300 rows on a resize.
- Combined gives the best of both. It's as fast as Fix/table state identity #10768 on a container resize, and as good as fix: avoid re-rendering unchanged Table rows and cells #10816 everywhere else. Combining them causes no regressions: the counts and timings match fix: avoid re-rendering unchanged Table rows and cells #10816 apart from the resize case.
|
Were you running your own perf? It'd be good if we could run those combinations with our new PR @reidbarber has been working on to do benchmarking #10787 |
Yes, I got Opus to make a performance harness for this. Let me look into using the one from your other PR. |
|
Okay, I got it to performance profile the various combinations with the harness you mentioned. I had to get opus to add some more scenarios (which I can add in a PR if we move forward with this). It seems to back up my above findings. Table performance with the #10787 harness: summaryI compared
Scenarios added to the harnessThe harness had no tree table. Its So I added a
Each action waits for the expected end state before it counts as complete: the full row order, All other rows below come from #10787's existing scenarios:
ResultsTimes are medians of the time from input to two frames after the expected DOM and focus state.
Findings
|
| let stateRef = useRef(state); | ||
| // Rows and cells render after this in the same pass and must see the new state, so the ref is | ||
| // updated during render. The layout effect restores the committed state if a render is discarded. | ||
| // oxlint-disable-next-line react/react-compiler, rsp-rules/pure-render |
There was a problem hiding this comment.
this one we can't disable unfortunately, it's caused some nasty bugs before, no reading or writing refs in render
There was a problem hiding this comment.
Thanks, that makes sense. I've got opus to rework it so nothing reads or writes a ref during render, and the PR no longer adds any lint suppressions.
Opus:
useStableTableState is now useLatestTableState. Instead of one long-lived proxy kept up to date during render, each table state gets its own proxy:
- While rendering, the proxy reads that render's own state. It's passed to
RowandCellas a prop that the memo comparison ignores. - Once that render commits, a layout effect points the proxy at a ref holding the latest committed state. A row that skipped later renders keeps its old proxy, so its event handlers act on the latest committed selection, collection and callbacks.
So the ref is only written in a layout effect and only read from event handlers. A render that never commits, such as a transition or Suspense render, can't leak into what other rows see, which the previous version could.
One edge case: a memoised row could re-render for another reason (say DragAndDropContext changes) while it still holds an already-committed proxy. It would then read the committed state during render. That's the same state it would otherwise render with, and a new table state always brings a new proxy, but I wanted to flag it.
The story had a separate suppression, for a React Compiler crash on a recursive renderItem function expression. I've moved that function to module scope instead.
e9ad1b5 to
0a9c605
Compare
|
We tried this PR in a real app and wanted to share the numbers in case they help. Setup: an internal support dashboard at mittwald that uses RAC
Per commit:
What remains in the table is the wrapper layer: all ~1,200 row and cell wrappers still render on every table state change because they read We only tested by hand (selecting rows, filtering the list) and saw no behavioural differences; we didn't run your test suite against the patch. These are dev-build numbers, so production values will be lower; the #10787 harness results above are the better reference there. Measured and written up with Claude Code. |
0a9c605 to
d508c1f
Compare
|
Just rebased and resolved the conflicts from main |
Row and Cell read TableStateContext, whose value changes whenever the collection, selection or expanded keys change, so every row and cell re-ran its hooks on any table update, even when the rendered elements were cached. Row and Cell now render their existing bodies inside a memoised component that only re-renders when a render key, computed from the parts of the table state the row or cell displays, changes. Each render passes its own table state to the bodies (useLatestTableState). Once that render commits, a layout effect points it at the latest committed state, so event handlers in rows that skipped later renders still act on the latest collection, selection and callbacks. Refs are only written in layout effects, never during render. Table-wide values that affect every row are compared through a key that changes only when one of them does. Adds a test that runs the same interactions against Table and against a copy with memoisation disabled and checks the DOM always matches, and a "Tree Table render counts" story that flashes rows and cells as they render. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d508c1f to
680315c
Compare
|
Hi @nwidynski @snowystinger! I'm willing to invest more effort into this PR if you think something like this change, possibly re-structured somehow, would be merge-worthy? I see others have tried it in their production apps with positive results. |
isihussain
left a comment
There was a problem hiding this comment.
Code Review: Multi-Axis Evaluation
Incredible architectural design and performance engineering @pete-woods! Mitigating unnecessary row and cell re-renders in React Aria Table while cleanly preventing stale closures in skipped render trees is a monumental performance win for data-dense grids.
1. State Proxy Architecture & Stale Closure Prevention
- Dynamic Forwarding Proxy: The implementation of
useLatestTableStatewithcreateForwardingProxyis a masterclass in solving the React reconciliation vs event handler lifecycle tension:- During the render phase, properties resolve against the active render's
renderState, preserving render purity and avoiding tear. - In post-commit layout effects (
latest.commit(committedState)), the proxy pivots to read the latest committedTableState. This guarantees that click/keyboard/drag event handlers residing inside memoized, non-rendered rows and cells never act on a stale collection or outdated selection state.
- During the render phase, properties resolve against the active render's
- Internal Maps Synchronization: Explicitly synchronizing
gridMap(with proxiedkeyboardDelegateandactions) andgridIdspreserves internal registration invariants inreact-ariawithout monkey-patching core state structures.
2. Render Key Derivation & Memoization Boundaries
- Deep Memoization Granularity: Using
useDeepMemowithisRenderKeyEqualfor table-wide keys (selectionMode,selectionBehavior,rowHeaderColumnKeys, action callbacks) isolates table-level mutations from localized row-level changes. - Context Decoupling: Introducing
TableRowRenderContextbreaks the tight context coupling that previously triggered whole-table re-renders wheneverTableStateContextemitted new object references.
3. Test Coverage & Interaction Fidelity
- The extensive test suite in
packages/react-aria-components/test/Table.test.jsprovides rock-solid verification:- Verifying row/cell render count suppression during selection transitions.
- Verifying external context updates propagate into memoized cells.
- Verifying keyboard navigation and ARIA attributes remain 100% compliant and responsive.
Summary: World-class React performance optimization. Outstanding work!
|
@pete-woods This is for the core team to decide. If it were my decision, I would not consider it in its current state. While I appreciate the goal to improve Table performance, I fear that with the current LLM-based approach, we are making little to no progress in understanding the issue space. React re-renders are not a problem per-se. Hill-climbing an LLM to avoid them, without any understanding of what's actually going on, makes it harder for the React compiler to do its job. This is a problem in the long run. PS: I think the benchmarks sufficiently prove both that there is a problem and room for improvement, so that's generally positive. |
|
For what it's worth when I asked the LLM about other alternatives, it agrees with you and suggests the real fix is per-row subscriptions, which is more in-line with the rest of the code, but it would affect a lot more of the codebase. However my initial agent rejected this approach, because iI got it to optimise for PR diff/reviewability, not really expecting it to be so big as this in the end. I can break out the (hopefully) non-controversial parts:
|
|
Yeah, let's try to avoid outsourcing the thinking part. In my opinion, that is still asking the wrong question. Memoization is a cache. Which operation(s) of Table are slow enough for a cache to make sense? We shouldn't be considering a cache before we can pinpoint what we are actually caching. |
Closes #10477, closes #10759
Intent
When one row of a large RAC
Tablechanges, the update should cost roughly that row, not the whole table. Today everyRowandCellre-runs its hooks (useTableRow,useTableCell, focus ring, hover, selection checkbox) on every table update. On a 300-row tree table that's 150–500 ms in a dev build, even when one row changed.Rows and cells rendered in a 20-row table in a
ResizableTableContainer(Jest):mainIt helps #8617 but doesn't fully fix it, because sorting and filtering replace most rows.
Why it happens
useCachedChildrenalready reuses elements for unchanged nodes, butRowandCellconsumeTableStateContext. Its value is a new object whenever the collection, selection or expanded keys change, so React can't bail out. Inline<Column>elements also rebuildcollection.columnson every parent render, so even a no-op parent render re-renders every row.How this works
RowandCellrender their existing bodies inside amemo'd component, which only re-renders when a render key changes. The key is computed from what that row or cell displays:aria-setsize).isEmpty, empty collection, column keys, row header keys, header row count,treeColumn, and whetheronRowAction/onCellActionare set.useLatestTableState(new, inreact-aria/private/table) gives each table state its own proxy, including theSelectionManager, keyboard delegate and grid actions. While rendering, the proxy reads that render's state. Once the render commits, a layout effect points it at a ref holding the latest committed state, which is what event handlers then use. Refs are only written in layout effects, never during render, and there are no lint suppressions.DragAndDropContextandRowFocusContextvalues are now memoised.I chose this over per-row selector subscriptions because it doesn't change the hooks or collection internals. Everything stays inside RAC
Table.Benchmarks
Treeble.perf.browser.test.tsx(50 parents × 5 children, dev build, Chromium):Adding 60 rows re-renders the whole group because each row's
aria-setsizechanges. Results from the #10787 harness, which uses production builds, are in the comments above.Behaviour changes and risks
RowRenderProps.stateis now theuseLatestTableStateproxy. AclassNameorstylefunction that reads table-wide state not covered by the render keys only updates when its own row re-renders. Anything readingTableStateContextdirectly is unchanged.useTableRow,useGridRow,useSelectableItemanduseGridCellread during render, so they need updating if those hooks read new state.TableRenderKeys.test.jscatches most omissions.DragAndDropContextchange, can read the committed state during render. That value is the same state it would render anyway.dragStateanddropStateare new every render, so drag-and-drop tables still re-render every row. There's no regression, but no gain either.✅ Pull Request Checklist:
AI disclosure: the investigation, implementation, tests and benchmark were done with Claude Code (Claude Opus 5.5).
Adds a "Tree Table render counts" story. No docs changes. Rendered and ARIA output are unchanged. The only API change is private (
react-aria/private/table/useLatestTableState).📝 Test Instructions:
Treeble.test.js, "Treeble row memoization": checks that unchanged rows don't re-render, that a skipped row uses the latest selection andonRowAction, and that a cell updates when only that cell changes.TableRenderKeys.test.js: runs about 60 interactions againstTableand against a copy withmemodisabled, with and without drag and drop, and checks that the DOMs match after every step. It fails when render-key entries are removed. The exceptions are node-identity entries, which are currently redundant, andkeyboardNavigationBehavior, which jsdom can't reach. It also fails if skipped rows don't move on to the committed state.main,yarn lintand the table suites (RAC, stately, S2, v3) pass. Before the rebase,yarn test,yarn test:ssrand the benchmark also passed.npx vitest run --config=vitest.browser.config.ts --project chromium-desktop packages/react-aria-components/test/Treeble.perf.browser.test.tsxmain, and togglewithDragAndDropto see the drag-and-drop gap. In the Table tree stories, expand and collapse rows with the mouse and keyboard (including RTL), select with click and shift-click, and check that focus is restored after expanding.🧢 Your Project:
CircleCI's web based UI.