How to preload pages with Nextjs
There are two next-specific ways you can navigate between pages in a Nextjs application (on the client side)
- Using the component from
next/link
(declarative) - Using the router object from the
useRouter
hook (imperative)
We're going to look at prefetching in both cases
Preloading with Link component
The Link component has a very simple api, just pass a href
prop with the relative url you want to navigate to and it just works, like the default <a>
tag. One thing to note however is that you need to still wrap an <a>
for it to work correctly.
import Link from 'next/link'
<Link href="/path/to/a/page">
<a>
Link text
</a>
</Link>
But how do you prefetch a page using the Link component? It happens automatically
Nextjs does this for every Link tag that is currently in the browser viewport. You can turn this off by setting the prefetch
prop to false
<Link href="/path/to/a/page" prefetch={false}>
<a>
Link text
</a>
</Link>
However, the page will still be prefetched on hover regardless of what value is passed to prefetch
Preloading with router.prefetch()
import { useRouter } from 'next/router'
import { useEffect } from 'react'
function Page() {
useEffect(() => {
router.prefetch('/path/to/page')
}, [])
return // jsx here
}
It's as simple as that! Now you might ask, in what scenario does it make sense to do this?
A prime example will be on a multi-part blog post. You can prefetch the next page while the user reads the current page, making transition appear instantaneous.
See the docs for more usage examples