Nextjs Fundamentals · Navigation

Programmatic navigation

`useRouter`

Programmatic navigation

When you need to navigate from code — after a form submits, a condition passes, or a button handler runs — use the useRouter hook. In the App Router it is imported from next/navigation, not the Pages Router's next/router:

'use client';

import { useRouter } from 'next/navigation';

export function CheckoutButton() {
  const router = useRouter();
  return <button onClick={() => router.push('/checkout')}>Checkout</button>;
}

useRouter is a Client Component hook, so the file needs 'use client' at the top. It returns a router object with a few methods:

  • router.push(href) navigates and adds a new entry to the browser history.
  • router.replace(href) navigates without adding a history entry.
  • router.back() and router.forward() move through the history stack.
  • router.refresh() re-fetches the current route and re-renders Server Components without losing client state.
  • router.prefetch(href) starts a prefetch of a route before it is visited.

Reach for <Link> first: it is prefetched automatically and gives users a real anchor they can open in a new tab. useRouter is for the cases a link cannot cover. Both push and replace scroll to the top by default; pass { scroll: false } to keep the current position.

You are about to answer a short quiz on useRouter.

  1. In the App Router, `useRouter` is imported from `next/navigation`.
  2. `useRouter` can only be called inside a ___ Component.
  3. `router.push('/dashboard')` adds a new entry to the browser history stack.
  4. `router.___('/dashboard')` navigates without adding a new history entry.
  5. `router.refresh()` re-fetches the current route and re-renders Server Components.
  6. You should prefer `useRouter` over `<Link>` for ordinary in-app navigation.