In this blog, we are going to discuss the Shallow routing in NextJs.
In Next.js, shallow routing updates the URL without reloading or refetching data. It changes the route on the client side while keeping the current page mounted.
This improves user experience by making transitions faster and smoother. The page isn’t fully refreshed, data isn’t refetched, and the app stays responsive while preserving its current state.
To use shallow routing, you can use the useRouter hook from the next/router module,
which provides access to the router instance. Then, you can call the push method on the router with the shallow option set to true.
The router object will also have access to the updated pathname. Changing the URL could mean adding a new query, so we could have the following code:
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
The URL will get updated to /?counter=10. and the page won’t get replaced, only the state of the route is changed.
Note that undefined is passed as the second argument to router.push. This represents the as parameter, which lets you show a different URL in the browser, useful when working with dynamic routes.
Keep in mind that this routing is only available for same-level URLs, meaning that you cannot use it to navigate to a completely different page hierarchy.
Also, some data-fetching methods such as getServerSideProps and getInitialProps will still be executed even with shallow routing.
Meanwhile, the Link component uses the shallow props to specify if the routing is shallow or not. In both cases router.push and Link default to false.
That’s all about the Shallow routing.
You can check out our other next js blogs: Click here
Happy coding 🙂

Be the first to comment.