Performance: Router cache on client
This affects page load speed and interaction responsiveness by reducing network requests and speeding up navigation.
import { useRouter } from 'next/router'; import { useState, useEffect } from 'react'; const cache = new Map(); function Page() { const router = useRouter(); const [pageData, setPageData] = useState(null); async function goToAbout() { if (cache.has('/about')) { setPageData(cache.get('/about')); } else { const res = await fetch('/about-data.json'); const data = await res.json(); cache.set('/about', data); setPageData(data); } router.push('/about'); } return <button onClick={goToAbout}>About</button>; }
import { useRouter } from 'next/router'; function Page() { const router = useRouter(); function goToAbout() { router.push('/about'); // no caching, fetches fresh data every time } return <button onClick={goToAbout}>About</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No client cache | High (new nodes on each page) | Multiple per navigation | High due to full repaint | [X] Bad |
| With client cache | Low (reuse nodes/data) | Single or none | Low due to partial repaint | [OK] Good |
router.prefetch() to load pages in advance.router.prefetch() loads the page and stores it in the client cache for faster navigation.import { useRouter } from 'next/router';
export default function Home() {
const router = useRouter();
router.prefetch('/about');
return <button onClick={() => router.push('/about')>Go to About</button>;
}router.prefetch('/about') inside the component, which loads and caches the /about page on the client.router.push('/about') navigates to the cached page, making the load instant without server fetch.import { useRouter } from 'next/router';
export default function Page() {
const router = useRouter();
function handleClick() {
router.prefetch('/contact')
}
return <button onClick={handleClick}>Load Contact</button>;
}router.prefetch('/contact') inside an event handler is valid and triggers prefetch when the button is clicked.useRouter is properly used inside the functional component./about and /contact when the homepage loads?useEffect with empty dependencies is ideal.router.prefetch() directly in the component body runs on every render, which is inefficient. Using router.push() navigates instead of prefetching. getServerSideProps runs on server, not client cache.Pass the test and this pattern moves unknown