tezvyn:

Next.js Router Cache: Instant Client-Side Navigation

AI-drafted, machine-checkedSource: nextjs.orgintermediate

The Next.js Router Cache is a client-side, in-memory cache that makes navigation feel instant by storing the rendered UI of visited routes. It's why navigating with `<Link>` is fast. The footgun: it caches UI, not data, so stale content can appear.

WHY IT EXISTS: Traditional web apps re-fetch and re-render everything on navigation, which is slow. The Next.js App Router aims for the best of both: server-centric rendering with SPA-like navigation speed. The Router Cache is the key mechanism that enables this fast, client-side navigation without losing the benefits of Server Components.

THE MENTAL MODEL: The Router Cache is an in-memory cache that lives on the client (in the browser) for the duration of a user session. It stores the React Server Component (RSC) payload—essentially the pre-rendered UI—for every route segment you visit. When you navigate back to a page, Next.js pulls this payload from the cache and renders it instantly, avoiding a round trip to the server.

HOW IT WORKS: When you navigate to a new route for the first time using the <Link> component, Next.js fetches the RSC payload from the server and stores it in the Router Cache. If you navigate away and then back, Next.js checks the cache first. If a fresh payload exists, it's used immediately. The cache is automatically invalidated on a hard refresh, but for dynamic data, you must manually trigger invalidation using router.refresh() or revalidation functions like revalidatePath.

WHEN TO USE IT: You are always using it when building with the Next.js App Router. It's not an opt-in feature; it's the default behavior that makes navigation with <Link> fast. It's particularly effective for pages that are mostly static or where content doesn't change frequently between user navigations.

WHEN NOT TO USE IT: You can't really "not use" it, but you need to manage it. The primary footgun is assuming it's a data cache. If a page displays data that can be changed by another action (e.g., a form submission), navigating back to it might show stale UI. In these cases, you must implement a strategy to invalidate the cache, such as calling router.refresh() after the mutation.

ONE CANONICAL EXAMPLE: Imagine a blog. You click from the homepage to "Post A". Next.js fetches and caches the UI for Post A. You then click to "Post B", and its UI is also cached. If you now use the browser's back button to return to "Post A", the page loads instantly from the Router Cache without hitting the server. If a new comment was added, you would need to programmatically invalidate the cache to see it.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.