Using Session Storage for Scroll Restoration
Showcase how session storage can be utilized to save scroll position state across pages and how to retrieve it for scroll restoration in TanStack Router based applications.
import { useLayoutEffect } from 'react';
import { useLocation } from 'react-router-dom';
Imports necessary hooks from React and React Router.
const saveScrollPosition = () => {
sessionStorage.setItem('scrollPosition', window.scrollY.toString());
};
Function to save the current scroll position to session storage.
const restoreScrollPosition = () => {
const savedPosition = sessionStorage.getItem('scrollPosition');
if (savedPosition) {
window.scrollTo(0, parseInt(savedPosition, 10));
}
};
Function to restore scroll position from session storage.
const useScrollRestoration = () => {
const location = useLocation();
useLayoutEffect(() => {
restoreScrollPosition();
return () => saveScrollPosition();
}, [location.pathname]);
};
Custom hook using `useLayoutEffect` to restore the scroll position when the component mounts, and save the scroll position when the component unmounts, based on the path change.