In linking 2 pages with Next.js I mentioned how the Link
Next.js component can be used to create links between 2 pages, and when you use it, Next.js transparently handles frontend routing for us, so when a user clicks a link, frontend takes care of showing the new page without triggering a new client/server request and response cycle, as it normally happens with web pages.
There’s another thing that Next.js does for you when you use Link
.
As soon as an element wrapped within <Link>
appears in the viewport (which means it’s visible to the website user), Next.js prefetches the URL it points to, as long as it’s a local link (on your website), making the application super fast to the viewer.
This behavior is only being triggered in production mode (we’ll talk about this in-depth later), which means you have to stop the application if you are running it with npm run dev
, compile your production bundle with npm run build
and run it with npm run start
instead.
Using the Network inspector in the DevTools you’ll notice that any links above the fold, at page load, start the prefetching as soon as the load
event has been fired on your page (triggered when the page is fully loaded, and happens after the DOMContentLoaded
event).
Any other Link
tag not in the viewport will be prefetched when the user scrolls and it
Prefetching is automatic on high speed connections (Wifi and 3g+ connections, unless the browser sends the Save-Data
HTTP Header.
You can opt out from prefetching individual Link
instances by setting the prefetch
prop to false
:
<Link href="/a-link" prefetch={false}>
<a>A link</a>
</Link>
Download my free Next.js Handbook
More next tutorials:
- Getting started with Next.js
- Next.js vs Gatsby vs create-react-app
- How to install Next.js
- Linking two pages in Next.js using Link
- Dynamic content in Next.js with the router
- Feed data to a Next.js component using getInitialProps
- Styling Next.js components using CSS
- Prefetching content in Next.js
- Using the router to detect the active link in Next.js
- View source to confirm SSR is working in Next.js
- Next.js: populate the head tag with custom tags
- Deploying a Next.js application on Now
- Next.js: run code only on the server side or client side in Next.js
- Deploying a Next.js app in production
- How to analyze the Next.js app bundles
- Lazy loading modules in Next.js
- Adding a wrapper component to your Next.js app
- The icons added by Next.js to your app
- The Next.js App Bundles
- How to use the Next.js Router
- How to use Next.js API Routes
- How to get cookies server-side in a Next.js app
- How to change a Next.js app port