0
0
NextJSframework~5 mins

Router cache on client in NextJS

Choose your learning style9 modes available
Introduction

Router cache on client helps your app load pages faster by remembering data and components you already visited. It avoids reloading everything from the server each time.

When users navigate back and forth between pages quickly.
When you want to reduce loading time and improve user experience.
When your app has many pages with repeated visits.
When you want to save bandwidth by not fetching the same data again.
When you want smooth transitions without flickering or delays.
Syntax
NextJS
import { useRouter } from 'next/navigation';

const router = useRouter();

router.prefetch('/page');

router.prefetch() tells Next.js to load the page in the background before the user visits it.

This caching happens automatically for visited pages, but prefetch helps prepare pages early.

Examples
This example preloads the About page so it opens faster when clicked.
NextJS
'use client';

import React from 'react';
import { useRouter } from 'next/navigation';

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

  // Prefetch about page when component mounts
  React.useEffect(() => {
    router.prefetch('/about');
  }, []);

  return <button onClick={() => router.push('/about')}>Go to About</button>;
}
Here, prefetch is turned off for the Contact link to save bandwidth if you don't expect users to visit it soon.
NextJS
import Link from 'next/link';

export default function Nav() {
  return <nav>
    <Link href="/contact" prefetch={false}>Contact</Link>
  </nav>;
}
Sample Program

This component preloads the About page when the Home page loads. Clicking the button navigates instantly because the page is cached.

NextJS
'use client';

import { useRouter } from 'next/navigation';
import React from 'react';

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

  React.useEffect(() => {
    // Prefetch the About page to cache it on client
    router.prefetch('/about');
  }, []);

  return (
    <main>
      <h1>Home Page</h1>
      <button onClick={() => router.push('/about')}>Go to About</button>
    </main>
  );
}
OutputSuccess
Important Notes

Next.js automatically caches pages you visit, so you usually don't need to manage cache manually.

Use router.prefetch() to improve speed for pages users are likely to visit next.

Be mindful of network usage when prefetching many pages.

Summary

Router cache on client speeds up navigation by storing visited pages.

Use router.prefetch() to load pages before users click links.

This improves user experience with faster page loads and smoother transitions.