0
0
NextjsConceptBeginner · 3 min read

Router Cache in Next.js: What It Is and How It Works

In Next.js, router cache refers to the mechanism that stores previously loaded pages in memory to speed up client-side navigation. When you navigate between pages, Next.js uses this cache to instantly show pages without reloading data or components again.
⚙️

How It Works

Imagine you have a photo album and you flip through pages. Instead of looking for each photo from scratch every time, you keep the photos you recently viewed on your desk for quick access. Similarly, Next.js router cache keeps recently visited pages ready in memory.

This cache stores the JavaScript and data for pages you have already visited. When you click a link to go back or to a page you visited before, Next.js uses the cached version to show the page instantly without waiting for the network or reloading components.

This makes navigation feel very fast and smooth, like flipping through a well-organized photo album instead of waiting for each photo to load from a distant shelf.

💻

Example

This example shows how Next.js prefetches and caches pages automatically when using the next/link component for navigation.

javascript
import Link from 'next/link';
import { useRouter } from 'next/router';

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

  return (
    <div>
      <h1>Home Page</h1>
      <Link href="/about">
        Go to About
      </Link>
      <button onClick={() => router.push('/about')}>Go to About Programmatically</button>
    </div>
  );
}

// The About page
export function About() {
  return <h1>About Page</h1>;
}
Output
Home Page [Link: Go to About] [Button: Go to About Programmatically]
🎯

When to Use

Router cache in Next.js is used automatically to improve user experience by making page transitions faster. You benefit from it especially in apps with multiple pages where users navigate back and forth.

Use it when you want smooth client-side navigation without full page reloads. It is great for dashboards, blogs, e-commerce sites, or any app where users browse many pages.

However, if your pages show very dynamic data that changes often, you might want to control caching carefully to avoid showing stale content.

Key Points

  • Next.js router cache stores visited pages in memory for fast navigation.
  • It works automatically with next/link and client-side routing.
  • Cache improves user experience by reducing load times between pages.
  • Be mindful of caching when pages have frequently changing data.

Key Takeaways

Next.js router cache speeds up page navigation by storing visited pages in memory.
It works automatically with client-side routing using next/link and router.push.
Router cache makes your app feel faster and smoother without full page reloads.
Use router cache for apps with multiple pages and mostly static content.
Control caching carefully if your pages show frequently updated data.