Performance: Programmatic navigation (useRouter)
This affects page load speed and interaction responsiveness by controlling client-side navigation without full page reloads.
import { useRouter } from 'next/router'; const router = useRouter(); router.push('/about');
window.location.href = '/about';
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| window.location.href navigation | Full DOM reload | Multiple reflows | High paint cost | [X] Bad |
| useRouter.push navigation | Partial DOM update | Minimal reflows | Low paint cost | [OK] Good |
useRouter hook from next/navigation allow you to do in a Next.js app?useRouter hook provides methods to change pages in code, not by user clicking links.useRouter from Next.js 14+ for programmatic navigation?useRouter is imported from next/navigation, not next/router.import { useRouter } from 'next/navigation';
export default function Home() {
const router = useRouter();
return (
<button onClick={() => router.push('/about')}>Go to About</button>
);
}router.push('/about') method navigates to the '/about' page and adds a new entry in the browser history stack.useRouter for navigation:import { useRouter } from 'next/navigation';
export default function Page() {
const router = useRouter;
return (
<button onClick={() => router.push('/contact')}>Contact</button>
);
}const router = useRouter; without calling it as a function. It should be useRouter().useRouter should you use and how?const router = useRouter(); // Your code here
router.push() adds a new entry to browser history, while router.replace() swaps the current entry.router.replace('/newpage').router.replace('/newpage') to replace current history entry [OK]Pass the test and this pattern moves unknown