0
0
NextJSframework~5 mins

Route prefetching behavior in NextJS

Choose your learning style9 modes available
Introduction

Route prefetching helps your app load pages faster by getting them ready before you click. It makes navigation smooth and quick.

When you want to speed up page loading for links users are likely to click next.
When you want to improve user experience by reducing waiting time between pages.
When you have a multi-page app and want to prepare pages in the background.
When you want to optimize performance on slow networks by preloading important routes.
Syntax
NextJS
import Link from 'next/link';

<Link href="/about" prefetch={true}>About</Link>

The prefetch prop on Link controls if Next.js preloads the page.

By default, Next.js prefetches pages in the viewport when using next/link.

Examples
This disables prefetching for the Contact page link.
NextJS
<Link href="/contact" prefetch={false}>Contact</Link>
Default behavior: Next.js prefetches the Blog page when the link is visible.
NextJS
<Link href="/blog">Blog</Link>
Manually prefetch the Dashboard page on component load using the router.
NextJS
import { useEffect } from 'react';
import { useRouter } from 'next/router';

const Component = () => {
  const router = useRouter();

  useEffect(() => {
    router.prefetch('/dashboard');
  }, [router]);

  return <div>Dashboard Prefetch Example</div>;
};
Sample Program

This component shows three links with different prefetch behaviors. The About page is prefetched manually on load, Contact disables prefetch, and Blog uses default prefetching.

NextJS
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function Home() {
  const router = useRouter();

  useEffect(() => {
    // Manually prefetch the /about page
    router.prefetch('/about');
  }, [router]);

  return (
    <main>
      <h1>Welcome to Home</h1>
      <nav>
        <ul>
          <li><Link href="/about">About (prefetched manually)</Link></li>
          <li><Link href="/contact" prefetch={false}>Contact (no prefetch)</Link></li>
          <li><Link href="/blog">Blog (default prefetch)</Link></li>
        </ul>
      </nav>
    </main>
  );
}
OutputSuccess
Important Notes

Prefetching only works in production builds, not in development mode.

Prefetching uses idle browser time to avoid slowing down the main work.

Too much prefetching can waste bandwidth, so use it wisely.

Summary

Route prefetching loads pages in the background to speed up navigation.

You can control prefetching with the prefetch prop on Link or manually with router.prefetch().

Use prefetching to improve user experience but avoid overusing it to save bandwidth.