Use built-in Next.js scroll restoration machinery

This commit is contained in:
Marshall Polaris 2022-08-28 02:37:19 -07:00
parent d8b3fed46d
commit 50d7782e2c
3 changed files with 1 additions and 44 deletions

View File

@ -1,41 +0,0 @@
import { useRouter } from 'next/router'
import { useEffect, useRef } from 'react'
// From: https://jak-ch-ll.medium.com/next-js-preserve-scroll-history-334cf699802a
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])
}

View File

@ -8,6 +8,7 @@ module.exports = {
reactStrictMode: true,
optimizeFonts: false,
experimental: {
scrollRestoration: true,
externalDir: true,
modularizeImports: {
'@heroicons/react/solid/?(((\\w*)?/?)*)': {

View File

@ -3,7 +3,6 @@ import type { AppProps } from 'next/app'
import { useEffect } from 'react'
import Head from 'next/head'
import Script from 'next/script'
import { usePreserveScroll } from 'web/hooks/use-preserve-scroll'
import { QueryClient, QueryClientProvider } from 'react-query'
import { AuthProvider } from 'web/components/auth-context'
import Welcome from 'web/components/onboarding/welcome'
@ -26,8 +25,6 @@ function printBuildInfo() {
}
function MyApp({ Component, pageProps }: AppProps) {
usePreserveScroll()
useEffect(printBuildInfo, [])
return (