Guides & Tutorials
Shallow Routing in Next.js
Hello!
Normally, I like to go deep with my posts, but let's not this time: Let's talk about shallow routing in Next.js!
What the heck is shallow routing?
Shallow routing is when you change your website's URL without re-running data fetching methods again. In the case of Next.js, it means you have one page component that covers multiple URLs! This is particularly useful for adding query strings, and routes that might explain the content of your pages as they change to user behavior.
How do I use it?
If you'd like to use shallow routing in your applications, you don't do shallow routing with the <Link>
component built into the framework, which is what you might expect. Use the built-in useRouter
hook, and add { shallow: true }
to your router.push
commands, like so!
useEffect(() => {
router.push('/some-other-route', undefined, { shallow: true })
}, [someVariable])
Wanna see it in action? In this Choose Your Own Adventure app, you can navigate through the story without querying the database multiple times for new characters to be a part of it! The code for the routing is here, and you can see how the entire project was built in this demo video.
Can I do this myself?
Heck yeah you can! Here's a starter project for ya to get building:
(Clicking this button will deploy a Next.js starter project to Netlify, and clone it to your chosen Git provider)