0
0
NextjsHow-ToBeginner · 3 min read

How to Navigate Programmatically in Next.js with useRouter

In Next.js, you navigate programmatically by using the useRouter hook from next/router. Call router.push('/path') to change routes without a page reload.
📐

Syntax

Use the useRouter hook to get the router object. Then call router.push(url, as, options) to navigate.

  • url: The path or URL to navigate to.
  • as (optional): The URL shown in the browser (for dynamic routes).
  • options (optional): Object with options like shallow to avoid full reload.
javascript
import { useRouter } from 'next/router';

function Component() {
  const router = useRouter();

  function goToPage() {
    router.push('/target-page');
  }

  return null;
}
💻

Example

This example shows a button that navigates to the /about page when clicked, using router.push.

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

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

  const handleClick = () => {
    router.push('/about');
  };

  return (
    <main style={{ padding: '2rem' }}>
      <h1>Home Page</h1>
      <button onClick={handleClick} aria-label="Go to About page">
        Go to About
      </button>
    </main>
  );
}
Output
A page with a heading 'Home Page' and a button labeled 'Go to About'. Clicking the button navigates to '/about' without reloading the page.
⚠️

Common Pitfalls

  • Forgetting to import useRouter from next/router.
  • Calling router.push outside a React component or before the router is ready.
  • Using window.location instead of router.push, which causes a full page reload.
  • Not handling asynchronous navigation properly if you need to wait for navigation to complete.
javascript
/* Wrong way: causes full page reload */
function Wrong() {
  function go() {
    window.location.href = '/about';
  }
  return <button onClick={go}>Go</button>;
}

/* Right way: client-side navigation without reload */
import { useRouter } from 'next/router';
function Right() {
  const router = useRouter();
  function go() {
    router.push('/about');
  }
  return <button onClick={go}>Go</button>;
}
📊

Quick Reference

Summary tips for programmatic navigation in Next.js:

  • Always use useRouter hook inside React components.
  • Use router.push('/path') for navigation without reload.
  • Use router.replace('/path') to replace history instead of adding a new entry.
  • Use router.prefetch('/path') to load pages in advance for faster navigation.
  • Handle dynamic routes by passing parameters in the URL string.

Key Takeaways

Use the useRouter hook from next/router to get the router object inside components.
Call router.push('/path') to navigate programmatically without reloading the page.
Avoid using window.location for navigation to keep client-side routing benefits.
router.replace('/path') changes the URL without adding a new history entry.
Prefetch pages with router.prefetch('/path') for faster user experience.