Skip to content
Closed
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
12 changes: 9 additions & 3 deletions packages/virtualized-lists/Lists/VirtualizedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -1017,9 +1017,7 @@ class VirtualizedList extends StateSafePureComponent<
onUpdateSeparators={this._onUpdateSeparators}
onCellFocusCapture={this._onCellFocusCapture}
onUnmount={this._onCellUnmount}
ref={ref => {
this._cellRefs[key] = ref;
}}
ref={this._captureCellRef}
renderItem={renderItem}
{...(shouldListenForLayout && {
onCellLayout: this._onCellLayout,
Expand Down Expand Up @@ -1610,6 +1608,14 @@ class VirtualizedList extends StateSafePureComponent<
}
};

// Stable, so React doesn't detach and reattach every cell's ref on each
// render. Unmounted cells are removed in `_onCellUnmount`.
_captureCellRef = (cellRenderer: null | CellRenderer<any>): void => {
if (cellRenderer != null) {
this._cellRefs[cellRenderer.props.cellKey] = cellRenderer;
}
};

_onCellUnmount = (cellKey: string) => {
delete this._cellRefs[cellKey];
this._listMetrics.notifyCellUnmounted(cellKey);
Expand Down
53 changes: 53 additions & 0 deletions packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,59 @@ describe('VirtualizedList', () => {
});
});

it('does not reattach cell refs when the list re-renders', async () => {
const listRef = createRef();
const items = generateItems(5);
let component;
await act(() => {
component = create(
<VirtualizedList ref={listRef} {...baseItemProps(items)} />,
);
});

const cellRefs = listRef.current._cellRefs;
const cellRefWrites = [];
listRef.current._cellRefs = new Proxy(cellRefs, {
set(target, cellKey, cellRenderer) {
cellRefWrites.push(cellKey);
target[cellKey] = cellRenderer;
return true;
},
});

await act(() => {
component.update(
<VirtualizedList
ref={listRef}
{...baseItemProps(items)}
extraData={1}
/>,
);
});

expect(cellRefWrites).toEqual([]);
expect(Object.keys(cellRefs)).toEqual(['0', '1', '2', '3', '4']);
});

it('removes cell refs when cells unmount', async () => {
const listRef = createRef();
let component;
await act(() => {
component = create(
<VirtualizedList ref={listRef} {...baseItemProps(generateItems(5))} />,
);
});

await act(() => {
component.update(
<VirtualizedList ref={listRef} {...baseItemProps(generateItems(2))} />,
);
});

expect(Object.keys(listRef.current._cellRefs)).toEqual(['0', '1']);
expect(listRef.current._cellRefs[0].props.cellKey).toBe(0);
});

it('handles nested lists', async () => {
let component;
await act(() => {
Expand Down
Loading