#Set URL without triggering navigation.
1 messages · Page 1 of 1 (latest)
Hi @lusty frigate. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can change the URL without triggering navigation by using the concept of shallow routing. Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps. You'll receive the updated pathname and the query via the router object, without losing state.
To enable shallow routing, set the shallow option to true. Here's an example:
import { useEffect } from 'react'
import { useRouter } from 'next/router'
// Current URL is '/'
function Page() {
const router = useRouter()
useEffect(() => {
// Always do navigations after the first render
router.push('/?counter=10', undefined, { shallow: true })
}, [])
useEffect(() => {
// The counter changed!
}, [router.query.counter])
}
export default Page
In this example, the URL will get updated to /?counter=10 and the page won't get replaced, only the state of the route is changed.