Blog>
Snippets

Manual Scroll Position Restoration with TanStack Router

This example demonstrates how to manually save and restore scroll position when navigating between routes in a SPA using TanStack Router.
import { createBrowserRouter, RouterProvider, useNavigation, useLocation } from 'tanstack/react-router';
let savedPositions = {};

const saveScrollPosition = () => {
  const key = location.key;
  savedPositions[key] = window.scrollY;
};

const restoreScrollPosition = () => {
  const key = location.key;
  const savedPosition = savedPositions[key] || 0;
  window.scrollTo(0, savedPosition);
};
This code creates a browser router and two functions for saving and restoring scroll positions using the TanStack Router. It utilizes `savedPositions` object to store the scroll positions for each route keyed by the route's unique location key.
const router = createBrowserRouter([
  // define your routes here
], {
  history: createBrowserHistory(),
});
This snippet is where you define your router and routes using `createBrowserRouter`. Each route can utilize the scroll restoration logic.
function useRestoreScroll() {
  const navigation = useNavigation();
  const location = useLocation();

  useEffect(() => {
    if (navigation.state === 'idle') {
      restoreScrollPosition();
    }
  }, [navigation.state]);

  useEffect(() => {
    return () => {
      saveScrollPosition();
    };
  }, [location]);
}
This custom hook `useRestoreScroll` listens for navigation changes. Once navigation is idle, it restores the scroll position for the new location. It also saves the scroll position before navigating away from the current page.
function App() {
  useRestoreScroll();

  return (
    <RouterProvider router={router} />
  );
}
This is your main App component where `useRestoreScroll` is called. It ensures that the scroll restoration logic is applied throughout your application.