import { useEffect , useLayoutEffect , useRef } from "react" ; import { useLocation } from "react-router-dom" ; type ScrollPos = [ number , number ] ; let savedScroll = null ; const homePaths = new Set ( [ "/" , "/locations" , "/bookings" ] ) ; export const useSaveScroll = ( ) => { const pathname = useLocation ( ) . pathname ; const previousPathname = usePrevious ( pathname ) ; useLayoutEffect ( ( ) => { const scrollPos = [ window . scrollX , window . scrollY ] ; const wasHome = previousPathname && homePaths . has ( previousPathname ) ; const isHome = homePaths . has ( pathname ) ; if ( wasHome && ! isHome ) { savedScroll = scrollPos ; window . scrollTo ( 0 , 0 ) ; } else if ( isHome && ! wasHome && savedScroll ) { window . scrollTo ( savedScroll [ 0 ] , savedScroll [ 1 ] ) ; } else if ( ! wasHome && ! isHome && previousPathname !== pathname ) { window . scrollTo ( 0 , 0 ) ; } } , [ pathname , previousPathname ] ) ; } ; function usePrevious < T > ( value ) { const ref = useRef < T > ( ) ; useEffect ( ( ) => { ref . current = value ; } , [ value ] ) ; return ref . current ; }