-
-
Save KirillTregubov/73beae93008b0a87f1fb2b6931b0d99d to your computer and use it in GitHub Desktop.
Next.js - Preserve Scroll History
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRouter } from "next/router" | |
import { useEffect, useRef } from "react" | |
export const usePreserveScroll = () => { | |
const router = useRouter() | |
const scrollPositions = useRef<{ [url: string]: number }>({}) | |
const isBack = useRef(false) | |
useEffect(() => { | |
router.beforePopState(() => { | |
isBack.current = true | |
return true | |
}) | |
const onRouteChangeStart = () => { | |
const url = router.pathname | |
scrollPositions.current[url] = window.scrollY | |
} | |
const onRouteChangeComplete = (url: any) => { | |
if (isBack.current && scrollPositions.current[url]) { | |
window.scroll({ | |
top: scrollPositions.current[url], | |
behavior: "auto", | |
}) | |
} | |
isBack.current = false | |
} | |
router.events.on("routeChangeStart", onRouteChangeStart) | |
router.events.on("routeChangeComplete", onRouteChangeComplete) | |
return () => { | |
router.events.off("routeChangeStart", onRouteChangeStart) | |
router.events.off("routeChangeComplete", onRouteChangeComplete) | |
} | |
}, [router]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment