import { useRouter } from 'next/router' ; import React , { ComponentProps , memo , useMemo } from 'react' ; import { QueryParamProvider } from 'use-query-params' ; type Props = Omit < ComponentProps < typeof QueryParamProvider > , 'ReactRouterRoute' | 'reachHistory' | 'history' | 'location' > ; const pathnameRegex = /[^?#]+/u ; function NextQueryParamProvider ( { children , ... rest } ) { const router = useRouter ( ) ; const match = router . asPath . match ( pathnameRegex ) ; const pathname = match ? match [ 0 ] : router . asPath ; const location = useMemo ( ( ) => { if ( typeof window !== 'undefined' ) { if ( router . isReady ) { return window . location ; } else { return { search : '' } as Location ; } } else { return { search : router . asPath . replace ( pathnameRegex , '' ) } as Location ; } } , [ router . asPath , router . isReady ] ) ; const history = useMemo ( ( ) => { function createUpdater ( routeFn ) { return function updater ( { hash , search } ) { routeFn ( { pathname : router . pathname , search , hash } , { pathname , search , hash } , { shallow : true , scroll : false } ) ; } ; } return { push : createUpdater ( router . push ) , replace : createUpdater ( router . replace ) , location } ; } , [ location , pathname , router ] ) ; return ( < QueryParamProvider { ... rest } history = { history } location = { location } > { children } < /QueryParamProvider>); } export default memo ( NextQueryParamProvider ) ;