typescriptbeginner

Link Prefetching Strategies

Control route prefetching behavior with next/link for optimal navigation performance.

typescript
import Link from 'next/link';

export function Navigation() {
  return (
    <nav className="flex gap-4">
      {/* Default: prefetches on viewport enter */}
      <Link href="/about">About</Link>

      {/* Disable prefetching (for rarely visited pages) */}
      <Link href="/admin" prefetch={false}>
        Admin
      </Link>

      {/* Programmatic navigation */}
      <ClientNavButton />
    </nav>
  );
}

// Client component with programmatic navigation
'use client';

import { useRouter } from 'next/navigation';

function ClientNavButton() {
  const router = useRouter();

  return (
    <div>
      {/* Prefetch on hover for likely navigation */}
      <button
        onMouseEnter={() => router.prefetch('/dashboard')}
        onClick={() => router.push('/dashboard')}
        className="px-4 py-2 bg-blue-500 rounded"
      >
        Go to Dashboard
      </button>

      {/* Replace current history entry */}
      <button onClick={() => router.replace('/new-page')}>
        Replace Page
      </button>

      {/* Refresh server components */}
      <button onClick={() => router.refresh()}>
        Refresh Data
      </button>

      {/* Go back */}
      <button onClick={() => router.back()}>Back</button>
    </div>
  );
}

Use Cases

  • navigation optimization
  • SPAs
  • reducing load times

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.