virtual: Scroll restoration doesn't work when using useWindowVirtualizer

Describe the bug

Scroll restoration doesn’t work when using useWindowVirtualizer.

I used react-virtualized and it works fine.

Your minimal, reproducible example

https://stackblitz.com/edit/next-typescript-pokptk-mucmhs?file=pages%2FanotherPage.tsx,pages%2Findex.tsx

Steps to reproduce

  1. scroll down
  2. click any link
  3. click to go back.

Expected behavior

The scroll position is restored.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Chrome

tanstack-virtual version

@tanstack/react-virtual@^3.0.0-beta.18

TypeScript version

No response

Additional context

No response

Terms & Code of Conduct

  • I agree to follow this project’s Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (2 by maintainers)

Most upvoted comments

I ended up restoring the scroll position manually. But I don’t need to do this with react-virtualized.

Edit 1: It is not good, even with restoring the scroll position manually. window.scrollTo just works when @tanstack/virtual was rendered completely - window.body.scrollHeight is changing when it is rendering. And there is no way to know when @tanstack/virtual is rendered completely.

Edit 2: I have restored scroll position by using the option: initialOffset

I have been trying this (but saving my scroll info in a state store using Zustand instead of history or whatever), and it full on doesn’t work. useWindowVirtualizer will sometimes just ignore initialOffset when it’s passed. And I can’t figure out any sort of deterministic explanation for when it will honor initialOffset and when it won’t.

Here’s some code; I’ve confirmed via print debugging that the scroll state is being saved and loaded appropriately, but the virtualizer will then just ignore it, except when it doesn’t. This is in Remix btw. (It’s storing and loading count because I need this to also work with pagination.)


// scroll store implementation
type ScrollState = {
  [route: string]: {
    offset: number;
    count: number;
    measurementsCache: VirtualItem[];
  };
};

type ScrollStore = {
  feeds: ScrollState;
  setScrollState: (route: string, state: ScrollState[string]) => void;
};

export const useScrollStore = create<ScrollStore>((set) => ({
  feeds: {},
  setScrollState: (route, state) =>
    set((store) => ({ feeds: { ...store.feeds, [route]: state } })),
}));

// used in exported components
const useVirtual = ({
  options,
  from,
  count,
}: {
  options: Omit<Parameters<typeof useWindowVirtualizer>[number], "count">;
  from: string;
  count: number;
}) => {
  const { feeds, setScrollState } = useScrollStore();
  const feedState = feeds[from];
  const location = useLocation();
  const navigation = useNavigation();

  const virtualizer = useWindowVirtualizer({
    ...options,
    count: feedState?.count ?? count,
    initialMeasurementsCache: feedState?.measurementsCache,
    initialOffset: feedState?.offset,
  });

  useEffect(() => {
    const isNavigatingAway =
      location.pathname === from && navigation.state !== "idle";
    if (isNavigatingAway) {
      setScrollState(from, {
        offset: virtualizer.scrollOffset ?? 0,
        count,
        measurementsCache: virtualizer.measurementsCache,
      });
    }
  }, [
    from,
    virtualizer.scrollOffset,
    virtualizer.measurementsCache,
    setScrollState,
    count,
    location,
    navigation,
  ]);

  return virtualizer;
};

I’ve just stumbled over this issue. I’m using tanstack-router and it doesn’t seem to be solved between these two packages.

For those interested, my resulting, simple, solution is to use the history’s state API. I like it because I don’t have to worry about the scroll restoration being triggered by the wrong screen. Also, no ids!

  // Read from the history state
  const {
    vtableItemCount: restoreItemCount,
    vtableOffset: restoreOffset,
    vtableMeasureCache: restoreMeasurementsCache,
  } = history.state || {};

  const virtualizer = useWindowVirtualizer({
    // itemCount is undefined in my case, until the API resolves.
    count: itemCount == undefined ? restoreItemCount : itemCount,
    // Restore the offset and also the measurements cache (when measuring, not required otherwise) 
    initialOffset: restoreOffset,
    initialMeasurementsCache: restoreMeasurementsCache,
  });

  // Update scrollpos and item count for scroll restoration.
  const scrollPos = useDebounce(useWindowScroll()[0].y, 500);
  React.useEffect(() => {
    history.replaceState(
      {
        vtableItemCount: itemCount,
        vtableOffset: scrollPos,
        vtableMeasureCache: virtualizer.measurementsCache,
      },
      document.title,
      window.location.href,
    );
  }, [itemCount, scrollPos, virtualizer.measurementsCache]);

Works perfectly!

@nuschk great! Thanks for the comment.

@Ugikie or even better you can save it on effect cleanup, checkout this react-router basic example https://stackblitz.com/edit/github-trynzk

The data I am displaying is dynamic

@Ugikie that is the case, basic when scroll is restored, virtualizer don’t remember prev read sizes and auto adjustment kiks in, you also need to store measurementsCache and restore it by passing via initialMeasurementsCache.

for example you can save it on click

onClick={() => {
  initialOffset = virtualizer.scrollOffset;
  initialMeasurementsCache = virtualizer.measurementsCache;
}}

@milad1367 This is my code while using next.js I saved the position when users scroll and restore the position by using scrollToOffset

import { useRouter } from "next/router"
import useMounted from "@libs/use_mounted"
import { useCallback, useEffect } from "react"
import { useScroll } from "@use-gesture/react"

export default function useRestoration({
  minHeight = null,
  conditinal = true,
  virtual = null
}: {
  virtual?: any
  minHeight?: number
  conditinal?: boolean
}) {
  const mounted = useMounted()
  const router = useRouter()
  const key = "myapp-scroll-restoration-" + router.pathname

  // useScrollRestoration(router)
  const scrollToLastPosition = useCallback(() => {
    try {
      const pos = sessionStorage.getItem(key)
      if (pos) {
        const parsedPos = JSON.parse(pos)

        if (
          document.body.scrollHeight > parsedPos.y &&
          (!minHeight || minHeight < document.body.scrollHeight) &&
          (-1 > window.scrollY - parsedPos.y ||
            window.scrollY - parsedPos.y > 0)
        ) {
          window.scrollTo(parsedPos.x, parsedPos.y)

          if (virtual) {
            virtual.scrollToOffset(parsedPos.y)
          }
          try {
            sessionStorage.removeItem(key)
          } catch (e) {
            console.error(e)
          }
        }
      }
    } catch (e) {
      console.error(e)
    }
  }, [key, minHeight, virtual])

  if (mounted && conditinal) {
    scrollToLastPosition()
  }

  function getPosition(): number {
    try {
      const pos = sessionStorage.getItem(key)
      if (pos) {
        const parsedPos = JSON.parse(pos)
        // sessionStorage.removeItem(key)

        return parsedPos.y
      }
      return 0
    } catch (e) {
      return 0
    }
  }

  const savePostion = useCallback(() => {
    const x = window.scrollX
    const y = window.scrollY
    try {
      const position = sessionStorage.getItem(key)
      if (!position) {
        sessionStorage.setItem(key, JSON.stringify({ x, y }))
      } else if (position) {
        if (y != 0) {
          sessionStorage.setItem(key, JSON.stringify({ x, y }))
        }
      }
    } catch (e) {
      console.error(e)
    }
  }, [key])

  useEffect(() => {
    if (conditinal) scrollToLastPosition()

    // router.events.on("routeChangeStart", savePostion)
    // // window.addEventListener("mousedown", savePostion)
    // return () => router.events.off("routeChangeStart", savePostion)
  }, [conditinal, scrollToLastPosition])

  useScroll(
    () => {
      savePostion()
    },
    { target: window, axis: "y", threshold: 10 }
  )
  return [scrollToLastPosition, getPosition]
}

@meotimdihia How did you fix this problem? because when you get the previous scroll position from local storage you need something like offset prop and not initialOffset! can you describe it, please?