Client Routing (useRouter)

Programmatic navigation and history manipulation.

Next.js5 min readConcept 38 of 65

Imperative Navigation

useRouter is a Client Component hook that lets you programmatically change routes.

While <Link> is always preferred for accessibility and SEO, useRouter is necessary when navigation happens as a result of an action (like a successful form submission or clicking a generic div).

History Control

The router gives you precise control over the browser's history stack.

You can push a new URL onto the stack, or replace the current URL so the user cannot click the 'Back' button to return to the previous page (crucial for authentication flows).

The Big Four Methods

router.push('/url'): Navigates to a new URL and adds it to the history stack.

router.replace('/url'): Navigates to a new URL but overwrites the current history entry.

router.back(): Navigates back one step in the browser history.

router.refresh(): Re-fetches the current route's Server Components from the server, without losing Client Component state (like scroll position or input values).

The History Stack

Interact with the routing methods below to see exactly how they manipulate the browser's internal History Stack.

Router API

import { useRouter } from 'next/navigation';
const router = useRouter();

Browser History Stack

[0]/
Current
Stack Bottom

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you import `useRouter` from `next/router` in an App Router component?
  2. 2When should you use `router.replace()` instead of `router.push()`?

Remember this

  • Always import useRouter from next/navigation, NEVER next/router.
  • push() adds a new entry to the browser's history stack.
  • replace() overwrites the current entry in the history stack.
  • refresh() refetches Server Components without resetting Client state.
  • Use <Link> for declarative navigation, and useRouter for programmatic navigation.

Done with this concept?

Mark it complete to track your progress. No login needed.