Linking and Navigating
Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook.
The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application.
A React component called Link is provided to do this client-side route transition.
The example above uses multiple links. Each one maps a path (href) to a known page:
/→pages/index.js/about→pages/about.js/blog/hello-world→pages/blog/[slug].js
Any <Link /> in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using Static Generation. The corresponding data for server-rendered routes is fetched only when the <Link /> is clicked.
Linking to dynamic paths
You can also use interpolation to create the path, which comes in handy for dynamic route segments. For example, to show a list of posts which have been passed to the component as a prop:
encodeURIComponent is used in the example to keep the path utf-8 compatible.
Alternatively, using a URL Object:
Now, instead of using interpolation to create the path, we use a URL object in href where:
pathnameis the name of the page in thepagesdirectory./blog/[slug]in this case.queryis an object with the dynamic segment.slugin this case.
Injecting the router
To access the router object in a React component you can use useRouter or withRouter.
In general we recommend using useRouter.
Imperative Routing
next/link should be able to cover most of your routing needs, but you can also do client-side navigations without it, take a look at the documentation for next/router.
The following example shows how to do basic page navigations with useRouter:
Shallow Routing
Examples
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 (added by useRouter or withRouter), without losing state.
To enable shallow routing, set the shallow option to true. Consider the following example:
The URL will get updated to /?counter=10 and the page won't get replaced, only the state of the route is changed.
You can also watch for URL changes via componentDidUpdate as shown below:
Caveats
Shallow routing only works for URL changes in the current page. For example, let's assume we have another page called pages/about.js, and you run this:
Since that's a new page, it'll unload the current page, load the new one and wait for data fetching even though we asked to do shallow routing.
When shallow routing is used with proxy it will not ensure the new page matches the current page like previously done without proxy. This is due to proxy being able to rewrite dynamically and can't be verified client-side without a data fetch which is skipped with shallow, so a shallow route change must always be treated as shallow.