An open source design system that's fully customizable and agent ready
TypeScript
fix(Table): prevent useXDSTableSelection from overrendering all rows (#1004)
Cindy Zhang9f0e79ce1896
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsxindex 829f97ee7b..da6c8b3958 100644--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx@@ -2,16 +2,15 @@* @file XDSTable.selection-perf.test.tsx* @input XDSTable, useXDSTableSelection, React testing utilities* @output Performance tests for selection plugin render behavior- * @position Test file; validates selection interaction correctness+ * @position Test file; validates selection interaction correctness and render efficiency*- * The selection plugin passes aria-selected and styles via transformBodyRow.- * Row re-renders on selection change are expected — checkbox content- * re-renders independently via SelectionContext.+ * The selection plugin uses an external store so that only the row whose+ * selection state changed re-renders — not all rows in the table body.*/import {describe, it, expect} from 'vitest';import {render, screen, act} from '@testing-library/react';-import {useState} from 'react';+import {useState, useMemo} from 'react';import userEvent from '@testing-library/user-event';import {XDSTable} from '../../XDSTable';import {useXDSTableSelection} from './useXDSTableSelection';@@ -33,7 +32,7 @@ const createTestData = (count: number): TestRow[] =>}));// =============================================================================-// Helper+// Helpers// =============================================================================function SelectionTestTable({data}: {data: TestRow[]}) {@@ -73,6 +72,67 @@ function SelectionTestTable({data}: {data: TestRow[]}) {);}+/**+ * Table with render counting per row.+ * Each row's renderCell increments a counter so we can verify+ * which rows re-rendered. Columns are memoized to isolate+ * selection-related re-renders from column-change re-renders.+ */+function SelectionRenderCountTable({+ data,+ renderCounts,+}: {+ data: TestRow[];+ renderCounts: Record<string, number>;+}) {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const columns = useMemo<XDSTableColumn<TestRow>[]>(+ () => [+ {+ key: 'name',+ header: 'Name',+ renderCell: (item: TestRow) => {+ renderCounts[item.id] = (renderCounts[item.id] ?? 0) + 1;+ return item.name;+ },+ },+ ],+ [renderCounts],+ );++ const selectionPlugin = useXDSTableSelection<TestRow>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(isAllSelected ? new Set(data.map(d => d.id)) : new Set());+ },+ getIsAllSelected: () =>+ data.length > 0 && data.every(d => selectedKeys.has(d.id)),+ getIsIndeterminate: () => {+ const count = data.filter(d => selectedKeys.has(d.id)).length;+ return count > 0 && count < data.length;+ },+ });++ return (+ <XDSTable+ data={data}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ );+}+// =============================================================================// Tests// =============================================================================@@ -129,4 +189,66 @@ describe('Selection plugin render performance', () => {expect(rows[4]).not.toHaveAttribute('aria-selected');expect(rows[5]).not.toHaveAttribute('aria-selected');});++ it('selecting a row should not re-render other rows', async () => {+ const user = userEvent.setup();+ const data = createTestData(5);+ const renderCounts: Record<string, number> = {};++ render(+ <SelectionRenderCountTable data={data} renderCounts={renderCounts} />,+ );++ // Record initial render counts+ const initialCounts = {...renderCounts};+ expect(Object.keys(initialCounts)).toHaveLength(5);++ // Select row-2+ const rowCheckboxes = screen.getAllByLabelText('Select row');+ await act(async () => {+ await user.click(rowCheckboxes[2]);+ });++ // Only row-2 should have re-rendered (count increased)+ // Other rows should keep their initial count+ for (const id of Object.keys(renderCounts)) {+ if (id === 'row-2') {+ // Selected row may re-render+ continue;+ }+ expect(renderCounts[id]).toBe(initialCounts[id]);+ }+ });++ it('deselecting a row should not re-render other rows', async () => {+ const user = userEvent.setup();+ const data = createTestData(5);+ const renderCounts: Record<string, number> = {};++ render(+ <SelectionRenderCountTable data={data} renderCounts={renderCounts} />,+ );++ // Select row-1 first+ const rowCheckboxes = screen.getAllByLabelText('Select row');+ await act(async () => {+ await user.click(rowCheckboxes[1]);+ });++ // Reset counts+ for (const key of Object.keys(renderCounts)) {+ renderCounts[key] = 0;+ }++ // Deselect row-1+ await act(async () => {+ await user.click(rowCheckboxes[1]);+ });++ // Only row-1 should have re-rendered+ for (const id of Object.keys(renderCounts)) {+ if (id === 'row-1') continue;+ expect(renderCounts[id]).toBe(0);+ }+ });});diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsxindex ce266fffe0..c10e0fdda0 100644--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx@@ -6,13 +6,34 @@* @output Exports useXDSTableSelection hook and UseXDSTableSelectionConfig type* @position Selection plugin; consumed by XDSTable via plugins prop*+ * ## Performance Architecture+ *+ * Selection state is managed via an external store (SelectionStore) so that+ * individual rows can subscribe to their own selection state independently.+ * When a row is selected/deselected, only that row re-renders — not the+ * entire table body.+ *+ * The plugin object returned by useXDSTableSelection is referentially stable+ * across renders. Selection-dependent rendering (aria-selected, background+ * highlight, checkbox state) is handled by store-subscribing components+ * (SelectionRowContent, SelectAllCheckbox) rather than in the plugin+ * transform functions.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Table/Table.doc.mjs (selection documentation)* - /packages/core/src/Table/index.ts (exports)*/--import {createContext, useContext, useMemo, type ReactNode} from 'react';+import {+ createContext,+ useContext,+ useCallback,+ useEffect,+ useRef,+ useMemo,+ useSyncExternalStore,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars, spacingVars} from '../../../theme/tokens.stylex';import {XDSCheckboxInput} from '../../../CheckboxInput';@@ -42,58 +63,173 @@ export interface UseXDSTableSelectionConfig<T extends Record<string, unknown>> {}// =============================================================================-// Selection Context (for checkbox components to re-render independently)+// Selection Store (external store for fine-grained row subscriptions)// =============================================================================-// eslint-disable-next-line @typescript-eslint/no-explicit-any-interface SelectionContextValue<T = any> {- getIsItemSelected: (item: T) => boolean;- onSelectItem: (event: {item: T; isSelected: boolean}) => void;- onSelectAll: (event: {isAllSelected: boolean}) => void;- getIsAllSelected: () => boolean;- getIsIndeterminate?: () => boolean;- getIsItemSelectable?: (item: T) => boolean;- getIsItemEnabled?: (item: T) => boolean;+/**+ * Lightweight external store that lets each row subscribe to selection+ * changes independently. When selection state changes, all subscribers are+ * notified but only components whose snapshot actually changed will re-render+ * (thanks to useSyncExternalStore's built-in equality check on the snapshot).+ */+interface SelectionStore<T extends Record<string, unknown>> {+ subscribe: (listener: () => void) => () => void;+ notify: () => void;+ getConfig: () => UseXDSTableSelectionConfig<T>;}-const SelectionContext = createContext<SelectionContextValue | null>(null);+function createSelectionStore<T extends Record<string, unknown>>(+ configRef: React.RefObject<UseXDSTableSelectionConfig<T>>,+): SelectionStore<T> {+ const listeners = new Set<() => void>();++ return {+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ notify() {+ for (const listener of listeners) {+ listener();+ }+ },+ getConfig() {+ return configRef.current;+ },+ };+}++// =============================================================================+// Selection Context+// =============================================================================++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const SelectionStoreContext = createContext<SelectionStore<any> | null>(null);++// =============================================================================+// Hooks for subscribing to selection state+// =============================================================================++/**+ * Subscribe to whether a specific item is selected.+ * Only triggers re-render when this item's selected state changes.+ */+function useIsItemSelected<T extends Record<string, unknown>>(+ store: SelectionStore<T>,+ item: T,+): boolean {+ const getSnapshot = useCallback(+ () => store.getConfig().getIsItemSelected(item),+ [store, item],+ );++ return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);+}// =============================================================================// Checkbox Components// =============================================================================function SelectAllCheckbox() {- const ctx = useContext(SelectionContext);- if (!ctx) return null;- const allSelected = ctx.getIsAllSelected();- const indeterminate = ctx.getIsIndeterminate?.() ?? false;+ const store = useContext(SelectionStoreContext);+ if (!store) return null;++ return <SelectAllCheckboxInner store={store} />;+}++/**+ * Inner component that subscribes to all-selected/indeterminate state.+ * Separated so the useCallback/useSyncExternalStore hooks are not+ * called conditionally (after the null guard).+ */+function SelectAllCheckboxInner<T extends Record<string, unknown>>({+ store,+}: {+ store: SelectionStore<T>;+}) {+ const getSnapshot = useCallback(() => {+ const config = store.getConfig();+ const allSelected = config.getIsAllSelected();+ const indeterminate = config.getIsIndeterminate?.() ?? false;+ return `${allSelected}:${indeterminate}`;+ }, [store]);++ const key = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);+ const [allSelectedStr, indeterminateStr] = key.split(':');+ const allSelected = allSelectedStr === 'true';+ const indeterminate = indeterminateStr === 'true';+return (<XDSCheckboxInputlabel="Select all rows"isLabelHiddenvalue={allSelected ? true : indeterminate ? 'indeterminate' : false}- onChange={() => ctx.onSelectAll({isAllSelected: !allSelected})}+ onChange={() =>+ store.getConfig().onSelectAll({isAllSelected: !allSelected})+ }size="sm"/>);}-function SelectionRowCheckbox<T>({item}: {item: T}) {- const ctx = useContext(SelectionContext);- if (!ctx) return null;- const selectable = ctx.getIsItemSelectable?.(item) ?? true;- if (!selectable) return null;- const selected = ctx.getIsItemSelected(item);- const enabled = ctx.getIsItemEnabled?.(item) ?? true;+/**+ * Row content component that subscribes to this item's selection state.+ * Handles the checkbox cell, aria-selected attribute, and selected row styling.+ * Only re-renders when this specific item's selection state changes.+ */+function SelectionRowContent<T extends Record<string, unknown>>({+ item,+ children,+}: {+ item: T;+ children: ReactNode;+}) {+ const store = useContext(SelectionStoreContext)!;+ const config = store.getConfig();+ const isSelected = useIsItemSelected(store, item);+ const selectable = config.getIsItemSelectable?.(item) ?? true;+ const enabled = config.getIsItemEnabled?.(item) ?? true;++ // Manage aria-selected and background color on the parent <tr> imperatively.+ // This avoids re-rendering the entire memoized row component — only this+ // content component re-renders when selection state changes.+ const cellRef = useRef<HTMLTableCellElement>(null);+ useEffect(() => {+ const tr = cellRef.current?.parentElement;+ if (!tr) return;+ if (isSelected) {+ tr.setAttribute('aria-selected', 'true');+ tr.style.backgroundColor = selectedBgColor;+ } else {+ tr.removeAttribute('aria-selected');+ tr.style.backgroundColor = '';+ }+ return () => {+ if (tr) {+ tr.removeAttribute('aria-selected');+ tr.style.backgroundColor = '';+ }+ };+ }, [isSelected]);+return (- <XDSCheckboxInput- label="Select row"- isLabelHidden- value={selected}- onChange={() => ctx.onSelectItem({item, isSelected: !selected})}- isDisabled={!enabled}- size="sm"- />+ <>+ <XDSTableCell ref={cellRef} xstyle={selectionCellStyles.base}>+ {selectable && (+ <XDSCheckboxInput+ label="Select row"+ isLabelHidden+ value={isSelected}+ onChange={() =>+ store.getConfig().onSelectItem({item, isSelected: !isSelected})+ }+ isDisabled={!enabled}+ size="sm"+ />+ )}+ </XDSTableCell>+ {children}+ </>);}@@ -101,11 +237,11 @@ function SelectionRowCheckbox<T>({item}: {item: T}) {// Styles// =============================================================================-const selectedRowStyles = stylex.create({- row: {- backgroundColor: colorVars['--color-accent-muted'],- },-});+/**+ * Resolved CSS variable for imperative style updates on the <tr>.+ * Uses the StyleX token directly so it stays in sync with the theme.+ */+const selectedBgColor = colorVars['--color-accent-muted'];const selectionCellStyles = stylex.create({base: {@@ -124,13 +260,34 @@ const selectionCellStyles = stylex.create({export function useXDSTableSelection<T extends Record<string, unknown>>(config: UseXDSTableSelectionConfig<T>,): TablePlugin<T> {+ // Keep config in a ref so the store always reads the latest version+ // without creating a new store or plugin object.+ const configRef = useRef(config);+ configRef.current = config;++ // Create the store once — it reads config via ref, so it never goes stale.+ const storeRef = useRef<SelectionStore<T> | null>(null);+ if (storeRef.current == null) {+ storeRef.current = createSelectionStore(configRef);+ }+ const store = storeRef.current;++ // Notify subscribers on every render — useSyncExternalStore will only+ // re-render components whose snapshot actually changed.+ useEffect(() => {+ store.notify();+ });++ // Return a stable plugin object — never changes after mount.+ // Selection-dependent rendering is handled by SelectionRowContent+ // and SelectAllCheckbox which subscribe to the store independently.return useMemo((): TablePlugin<T> => ({transformTableContext(children: ReactNode) {return (- <SelectionContext.Provider value={config}>+ <SelectionStoreContext.Provider value={store}>{children}- </SelectionContext.Provider>+ </SelectionStoreContext.Provider>);},@@ -149,26 +306,20 @@ export function useXDSTableSelection<T extends Record<string, unknown>>(},transformBodyRow(props: BodyRowRenderProps, item: T) {- const isSelected = config.getIsItemSelected(item);+ // Don't read selection state here — that would cause all rows+ // to re-render when any selection changes. Instead, delegate to+ // SelectionRowContent which subscribes to the store and only+ // re-renders when this specific item's selection state changes.return {- htmlProps: {- ...props.htmlProps,- 'aria-selected': isSelected || undefined,- },- styles: isSelected- ? [...props.styles, selectedRowStyles.row]- : props.styles,+ ...props,children: (- <>- <XDSTableCell xstyle={selectionCellStyles.base}>- <SelectionRowCheckbox item={item} />- </XDSTableCell>+ <SelectionRowContent item={item}>{props.children}- </>+ </SelectionRowContent>),};},}),- [config],+ [store],);}