Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

fix: no excessive sessionStorage reads #2451

Merged
merged 1 commit into from
Oct 9, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function InfiniteScrollListImpl<Item>(
const viewableItems = useRef<ViewToken[]>([]);
const parentRef = useRef<HTMLDivElement>(null);
const scrollMarginOffseRef = useRef<HTMLDivElement>(null);
const positionWasRestored = useRef<boolean>(false);

const parentOffsetRef = useRef(0);
const router = useRouter();
Expand All @@ -97,10 +98,11 @@ function InfiniteScrollListImpl<Item>(
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;
Expand All @@ -116,10 +118,11 @@ function InfiniteScrollListImpl<Item>(
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;
Expand All @@ -146,10 +149,18 @@ function InfiniteScrollListImpl<Item>(
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 () => {
Expand All @@ -160,11 +171,7 @@ function InfiniteScrollListImpl<Item>(
debouncedCallback
);
};
}, [
rowVirtualizer.scrollElement,
saveScrollPosition,
preserveScrollPosition,
]);
}, [rowVirtualizer.scrollElement, preserveScrollPosition, saveWhenIdle]);

const transformStyle = inverted ? { transform: "scaleY(-1)" } : {};

Expand Down
Loading