šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

What is NextJs prefetching and why should I care

Let's say you have a NextJs site with an index.js page that links to an about page and contact page:

import Link from 'next/link'
export default () => (<div>
        <h1>My Index page</h1>
        <nav>
        <Link href='/contact'><a>Contact</a></Link>
        <Link href='/about'><a>About</a></Link>
        </nav>
</div>)

Out of the box the NextJs framework will search for the Link tags and will preload and render the linked pages. So, when user decides to click a link like<Link href="/contact"> the transition to the target page will be blazing fast. This the prefetching functionaliaty in NextJs.

Some notes on prefetching:

  • it only works just for the local internal pages of the current site. For example, if we haveĀ Ā the google.com page will not be prefetched and so the transition will be slower
  • initilay, only the pages that have links in the visible viewport will be prefetched. NextJs willĀ watch as the user scrolls and brings new links into the viewport and will prefetched the content for those pages as their links appear on the screen
  • the Nextjs prefetching will work only if you use theĀ <Link>Ā tags. Using the plain oldĀ <a>Ā will not trigger a prefecthing. In general, itā€™s not a good idea to use the classic aā€™s in NextJs
  • what if the user press the back button? Nothing new will be loaded, because the browser still has the oldĀ index.jsĀ bundle in place, ready to instantly show theĀ /indexĀ route. Itā€™s all automatic.
  • if the server sends theĀ save-dataĀ HTTP header NextJs prefetching will not work
  • the prefetching behavior is only being triggered in production mode. In order to see it in action be sure to stop the app if in development mode. You will need to stop npm run dev and after useĀ npm run buildĀ andĀ npm run startĀ to use the production bundle. You can see here more instructions on how to setup our first NextJs project.
  • you can disable the prefeching of link by setting the prefetch atrribute: <Link href='/index' prefetch={false}>

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *