Skip to content

Commit 41b154f

Browse files
committed
clean stale notification sizes
1 parent 7f0df4c commit 41b154f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/hooks/useListPosition/useSizes.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,29 @@ export type NodeSizeMap = Record<string, NodeSize>;
1212
*/
1313
export default function useSizes() {
1414
const [sizeMap, setSizeMap] = React.useState<NodeSizeMap>({});
15+
const cleanUpMapRef = React.useRef<Record<string, ReturnType<typeof setTimeout>>>({});
1516

1617
const setNodeSize = React.useCallback((key: string, node: HTMLDivElement | null) => {
1718
if (!node) {
19+
cleanUpMapRef.current[key] = setTimeout(() => {
20+
delete cleanUpMapRef.current[key];
21+
22+
setSizeMap((prevSizeMap) => {
23+
if (!(key in prevSizeMap)) {
24+
return prevSizeMap;
25+
}
26+
27+
const nextSizeMap = { ...prevSizeMap };
28+
delete nextSizeMap[key];
29+
return nextSizeMap;
30+
});
31+
});
1832
return;
1933
}
2034

35+
clearTimeout(cleanUpMapRef.current[key]);
36+
delete cleanUpMapRef.current[key];
37+
2138
const nextSize = {
2239
width: node.offsetWidth,
2340
height: node.offsetHeight,
@@ -36,5 +53,14 @@ export default function useSizes() {
3653
});
3754
}, []);
3855

56+
React.useEffect(
57+
() => () => {
58+
Object.values(cleanUpMapRef.current).forEach((timer) => {
59+
clearTimeout(timer);
60+
});
61+
},
62+
[],
63+
);
64+
3965
return [sizeMap, setNodeSize] as const;
4066
}

0 commit comments

Comments
 (0)