How do you use the useRouter hook?

useRouter gives Client Components programmatic navigation. In the App Router, import it from next/navigation; it exposes push, replace, refresh, prefetch, back and forward. In the Pages Router, useRouter from next/router also exposes query, pathname and router events.

App Router (next/navigation)

  • router.push(href, { scroll }) navigates and adds a history entry.
  • router.replace(href) navigates without adding a history entry.
  • router.refresh() re-renders the current route on the server and merges the new RSC payload, keeping client state.
  • router.prefetch(href) prefetches a route manually.
  • router.back() / router.forward() move through history.

Reading the URL uses separate hooks: usePathname(), useSearchParams() and useParams(). There are no router.events; use usePathname and useSearchParams in an effect to react to navigation, or onNavigate on <Link>.

Rules

  • Only works in Client Components ("use client").
  • Do not call push during render; call it in event handlers or effects.
  • For server-side navigation in Server Components or Server Functions, use redirect() instead.
  • Mixing up the imports is a classic bug: next/router in the App Router throws "NextRouter was not mounted".

Prefer Link

Use <Link> for normal navigation. It renders a real <a>, so it supports opening in a new tab, prefetching and accessibility. Use useRouter when navigation follows logic, such as after a form succeeds.

Code example

tsx
1// app/search/search-box.tsx
2"use client";
3
4import { useRouter, usePathname, useSearchParams } from "next/navigation";
5import { useTransition } from "react";
6
7export function SearchBox() {
8 const router = useRouter();
9 const pathname = usePathname();
10 const searchParams = useSearchParams();
11 const [isPending, startTransition] = useTransition();
12
13 function onSearch(term: string) {
14 const params = new URLSearchParams(searchParams);
15 if (term) params.set("q", term);
16 else params.delete("q");
17
18 // replace: typing should not create a history entry per keystroke
19 startTransition(() => router.replace(`${pathname}?${params}`, { scroll: false }));
20 }
21
22 return (
23 <div>
24 <input defaultValue={searchParams.get("q") ?? ""} onChange={(e) => onSearch(e.target.value)} />
25 {isPending && <span>Searching…</span>}
26 <button onClick={() => router.refresh()}>Refresh results</button>
27 <button onClick={() => router.back()}>Back</button>
28 </div>
29 );
30}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app