Performance: Route prefetching behavior
Route prefetching affects page load speed by loading page code and data before the user navigates, improving perceived navigation speed.
import Link from 'next/link'; export default function Nav() { return ( <nav> <Link href="/about">About</Link> <Link href="/contact">Contact</Link> <Link href="/products">Products</Link> </nav> ); }
import Link from 'next/link'; export default function Nav() { return ( <nav> <Link href="/about" prefetch={true}>About</Link> <Link href="/contact" prefetch={true}>Contact</Link> <Link href="/products" prefetch={true}>Products</Link> </nav> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager prefetch all links | Minimal | 0 | Increased due to delayed main content | [X] Bad |
| Automatic viewport-based prefetch | Minimal | 0 | Minimal paint delay, faster navigation | [OK] Good |
Link component?prefetch prop usageprefetch prop accepts a boolean to enable or disable prefetching.prefetch={false} disables automatic prefetching on the Link.import Link from 'next/link';
export default function Home() {
return (
<div>
<Link href='/profile' prefetch>Go to Profile</Link>
</div>
);
}prefetch prop usageprefetch prop is present without a value, which means it is true.prefetch confirms this behavior.import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Page() {
const router = useRouter();
useEffect(() => {
router.prefetch('/dashboard');
}, []);
return <div>Welcome</div>;
}useRouteruseRouter for client navigation is imported from 'next/navigation', not 'next/router'.router.prefetchprefetch support, so prefetch won't work.useRouter import path is incorrect; it should be from 'next/navigation' -> Option DLinkprefetch={false} to prevent Next.js from prefetching immediately.onMouseEnter event to call router.prefetch() to load the page only when user shows interest.Pass the test and this pattern moves unknown