Blog>
Snippets

Route Prefetching with Link Components

Demonstrate how to use the Link component and its 'prefetch' prop to optimize navigation performance by prefetching route data in a Next.js app.
import Link from 'next/link';

// Normal link without prefetching
function Home() {
  return (
    <div>
      <Link href="/about">
        <a>About Us</a>
      </Link>
    </div>
  );
}
This is a simple usage of the Next.js Link component without prefetching. It renders a link that navigates to the /about page when clicked.
import Link from 'next/link';

// Link with prefetching enabled
function Home() {
  return (
    <div>
      <Link href="/about" prefetch>
        <a>About Us</a>
      </Link>
    </div>
  );
}
This example enhances the previous one by adding the 'prefetch' prop to the Link component. When the link is visible in the viewport, Next.js will prefetch the page at the href '/about' in the background, making the navigation faster when the user clicks the link.
import { useEffect } from 'react';
import Router from 'next/router';

// Prefetching manually on mouseover
function PrefetchOnHoverLink({ href, children }) {
  let prefetchTimeout = null;

  const prefetchLink = () => {
    // Add a slight delay to prevent prefetching when quickly moving the mouse
    prefetchTimeout = setTimeout(() => {
      Router.prefetch(href);
    }, 100);
  };

  const cancelPrefetch = () => {
    // If the prefetch timeout was set, clear it
    if (prefetchTimeout) {
      clearTimeout(prefetchTimeout);
    }
  };

  return (
    <Link href={href}>
      <a onMouseOver={prefetchLink} onMouseOut={cancelPrefetch}>
        {children}
      </a>
    </Link>
  );
}
This code snippet shows how to manually prefetch a Next.js route when the mouse hovers over a link. Prefetching is delayed by 100ms to avoid unnecessary prefetching during quick mouse movements. If the mouse leaves the link before the delay is over, the prefetch is canceled.