From 9e80734e9bf67f234798fab07c5c20a8587de7a2 Mon Sep 17 00:00:00 2001 From: Hirbod Mirjavadi Date: Mon, 9 Oct 2023 16:09:22 +0200 Subject: [PATCH] fix: no excessive sessionStorage reads --- .../infinite-scroll-list.web.tsx | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/design-system/infinite-scroll-list/infinite-scroll-list.web.tsx b/packages/design-system/infinite-scroll-list/infinite-scroll-list.web.tsx index 5249dcee85..2f04996307 100644 --- a/packages/design-system/infinite-scroll-list/infinite-scroll-list.web.tsx +++ b/packages/design-system/infinite-scroll-list/infinite-scroll-list.web.tsx @@ -80,6 +80,7 @@ function InfiniteScrollListImpl( const viewableItems = useRef([]); const parentRef = useRef(null); const scrollMarginOffseRef = useRef(null); + const positionWasRestored = useRef(false); const parentOffsetRef = useRef(0); const router = useRouter(); @@ -97,10 +98,11 @@ function InfiniteScrollListImpl( scrollMargin: parentOffsetRef.current, overscan: overscan ?? 2, initialOffset: (() => { - if (!preserveScrollPosition) return; + if (!preserveScrollPosition || positionWasRestored.current) return; const pos = sessionStorage.getItem(key); if (pos) { const parsedPos = Number(pos); + positionWasRestored.current = true; return parsedPos; } return 0; @@ -116,10 +118,11 @@ function InfiniteScrollListImpl( scrollMargin: parentOffsetRef.current, overscan: overscan ?? 4, initialOffset: (() => { - if (!preserveScrollPosition) return; + if (!preserveScrollPosition || positionWasRestored.current) return; const pos = sessionStorage.getItem(key); if (pos) { const parsedPos = Number(pos); + positionWasRestored.current = true; return parsedPos; } return 0; @@ -146,10 +149,18 @@ function InfiniteScrollListImpl( measurementsCache[key] = rowVirtualizer.measurementsCache; }); + const saveWhenIdle = useStableCallback(() => { + if ("requestIdleCallback" in window) { + window.requestIdleCallback(saveScrollPosition); + } else { + saveScrollPosition(); + } + }); + useEffect(() => { if (!preserveScrollPosition) return; - const debouncedCallback = debounce(saveScrollPosition, 100); + const debouncedCallback = debounce(saveWhenIdle, 100); rowVirtualizer.scrollElement?.addEventListener("scroll", debouncedCallback); return () => { @@ -160,11 +171,7 @@ function InfiniteScrollListImpl( debouncedCallback ); }; - }, [ - rowVirtualizer.scrollElement, - saveScrollPosition, - preserveScrollPosition, - ]); + }, [rowVirtualizer.scrollElement, preserveScrollPosition, saveWhenIdle]); const transformStyle = inverted ? { transform: "scaleY(-1)" } : {};