Skip to content

Commit fcd82ed

Browse files
committed
try to fix infinite rerender in virutalizedlist
1 parent 3e78e75 commit fcd82ed

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

apps/array/src/renderer/features/sessions/components/VirtualizedList.tsx

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
useCallback,
55
useEffect,
66
useLayoutEffect,
7+
useMemo,
78
useRef,
89
} from "react";
910

@@ -34,15 +35,32 @@ export function VirtualizedList<T>({
3435
const isAtBottomRef = useRef(true);
3536
const isInitialMountRef = useRef(true);
3637

38+
const itemsRef = useRef(items);
39+
const getItemKeyRef = useRef(getItemKey);
40+
itemsRef.current = items;
41+
getItemKeyRef.current = getItemKey;
42+
43+
const getScrollElement = useCallback(() => scrollRef.current, []);
44+
const getEstimateSize = useCallback(() => estimateSize, [estimateSize]);
45+
46+
const hasGetItemKey = getItemKey !== undefined;
47+
const stableGetItemKey = useMemo(() => {
48+
if (!hasGetItemKey) return undefined;
49+
return (index: number) => {
50+
const currentItems = itemsRef.current;
51+
const currentGetKey = getItemKeyRef.current;
52+
if (!currentGetKey || !currentItems[index]) return index;
53+
return currentGetKey(currentItems[index], index);
54+
};
55+
}, [hasGetItemKey]);
56+
3757
const virtualizer = useVirtualizer({
3858
count: items.length,
39-
getScrollElement: () => scrollRef.current,
40-
estimateSize: () => estimateSize,
59+
getScrollElement,
60+
estimateSize: getEstimateSize,
4161
overscan,
4262
gap,
43-
getItemKey: getItemKey
44-
? (index) => getItemKey(items[index], index)
45-
: undefined,
63+
getItemKey: stableGetItemKey,
4664
});
4765

4866
const handleScroll = useCallback(() => {
@@ -118,7 +136,6 @@ export function VirtualizedList<T>({
118136
{virtualItems.map((virtualRow) => (
119137
<div
120138
key={virtualRow.key}
121-
ref={virtualizer.measureElement}
122139
data-index={virtualRow.index}
123140
style={{
124141
position: "absolute",

0 commit comments

Comments
 (0)