Blog>
Snippets

Restoring Scroll Position on Navigation Back

Show how to programmatically restore the scroll position using the saved position from React Query's cache when the user navigates back to a previously visited page.
import { useQuery, useQueryClient } from 'react-query';

function MyComponent() {
  const queryClient = useQueryClient();
  const { data } = useQuery('myData', fetchDataFunction);

  useEffect(() => {
    // Assuming there's a saved position in the cache for this query
    const savedPosition = queryClient.getQueryData('scrollPosition');
    if (savedPosition) {
      window.scrollTo(0, savedPosition);
    }
  }, []);

  return (
    // Render your component
  );
}
This code uses React Query's useQueryClient to access the cache inside a React component. The useEffect hook is used to read a saved scroll position from the cache when the component mounts (or the user navigates back) and then scrolls the window to that position.
window.addEventListener('beforeunload', () => {
  const queryClient = useQueryClient();
  queryClient.setQueryData('scrollPosition', window.scrollY);
});
This snippet is intended to be added where it makes sense in your application logic. It listens for the 'beforeunload' event and saves the current scroll position into React Query's cache using useQueryClient. This ensures that when the user leaves the page, the current scroll position is saved and can be restored later.