Blog>
Snippets

Initializing TanStack Router for Scroll Restoration

Demonstrate how to initialize TanStack Router in a React SPA to enable default scroll restoration functionality.
import { BrowserRouter as Router } from 'react-router-dom';
import { useEffect } from 'react';
Imports necessary hooks and components from React and TanStack Router libraries.
function useScrollRestoration(routerLocation) {
  useEffect(() => {
    if (history.action === 'POP') {
      return;
    }
    window.scrollTo(0, 0);
  }, [routerLocation.pathname]);
}
Defines a custom hook for scroll restoration. It listens for changes in the route location, and scrolls to the top for every new navigation except when the navigation action is a 'POP' action, which would imply a backward navigation.
function App() {
  const location = useLocation();

  useScrollRestoration(location);

  return (
    <div>
      {/* Your route components here */}
    </div>
  );
}
In your main App component, use the custom scroll restoration hook by passing the current location from useLocation hook. This will ensure the page scrolls to the top on every navigation.
<Router>
  <App />
</Router>
Wraps your App component in the Router component to enable routing functionality in the React application.