|
4 | 4 | useCallback, |
5 | 5 | useEffect, |
6 | 6 | useLayoutEffect, |
| 7 | + useMemo, |
7 | 8 | useRef, |
8 | 9 | } from "react"; |
9 | 10 |
|
@@ -34,15 +35,32 @@ export function VirtualizedList<T>({ |
34 | 35 | const isAtBottomRef = useRef(true); |
35 | 36 | const isInitialMountRef = useRef(true); |
36 | 37 |
|
| 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 | + |
37 | 57 | const virtualizer = useVirtualizer({ |
38 | 58 | count: items.length, |
39 | | - getScrollElement: () => scrollRef.current, |
40 | | - estimateSize: () => estimateSize, |
| 59 | + getScrollElement, |
| 60 | + estimateSize: getEstimateSize, |
41 | 61 | overscan, |
42 | 62 | gap, |
43 | | - getItemKey: getItemKey |
44 | | - ? (index) => getItemKey(items[index], index) |
45 | | - : undefined, |
| 63 | + getItemKey: stableGetItemKey, |
46 | 64 | }); |
47 | 65 |
|
48 | 66 | const handleScroll = useCallback(() => { |
@@ -118,7 +136,6 @@ export function VirtualizedList<T>({ |
118 | 136 | {virtualItems.map((virtualRow) => ( |
119 | 137 | <div |
120 | 138 | key={virtualRow.key} |
121 | | - ref={virtualizer.measureElement} |
122 | 139 | data-index={virtualRow.index} |
123 | 140 | style={{ |
124 | 141 | position: "absolute", |
|
0 commit comments