Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Link and Router: useRouter, usePathname, and useSearchParams

Client navigation goes through Link and the router hooks, the server uses redirect(). The Suspense requirement, prefetch cost, and query string handling that breaks first.

~4 min readNext.js
#Next.js#Navigation#App Router#React
3D illustration of a URL bar wired to navigation hooks as modules feeding page cards

Quick Summary

Navigation in the App Router splits into two APIs and one rule: <Link> and the router functions are for client-side navigation, redirect() is for the server, and nothing on the client may be trusted to decide what data a route needs. useRouter, usePathname, useSearchParams, and useParams are all client hooks; pathname and searchParams are also available to Server Components, as props and as searchParams promise respectively.

useSearchParams() opts a route into client-side rendering unless it sits inside a <Suspense> boundary. That single behaviour causes "missing suspense boundary with useSearchParams" build errors on statically rendered pages, and the fix is structural, not a flag.

<Link> prefetches the next route when it enters the viewport, which is why hover feels instant and why 200 links in a table can burn bandwidth. prefetch={false} is the escape hatch for expensive routes.

Basic Syntax & Core Signatures

tsx
import Link from "next/link"; // Static href, typed, prefetched on viewport entry <Link href="/blog">Blog</Link> // Dynamic href: still a plain string, built at render <Link href={`/blog/${post.slug}`} prefetch={false}>...</Link> // Object href keeps query strings readable <Link href={{ pathname: "/blog", query: { page: 2, tag: "nextjs" } }}>Page 2</Link> // Replace the entry instead of pushing, and skip scroll restoration <Link href="/filters?sort=new" replace scroll={false}>Newest</Link> // Force a full document navigation (rarely correct in App Router) <Link href="/logout" prefetch={false} rel="nofollow">Log out</Link>
ts
// Client hooks "use client"; import { useRouter, usePathname, useSearchParams, useParams } from "next/navigation"; const router = useRouter(); router.push("/dashboard"); // adds a history entry router.replace("/dashboard"); // replaces the current entry router.refresh(); // re-fetches the current route's RSC payload router.back(); router.forward(); router.prefetch("/blog"); // imperative prefetch const pathname = usePathname() ?? "/"; const searchParams = useSearchParams(); const params = useParams<{ slug: string }>();
ts
// Server side import { redirect, permanentRedirect, notFound } from "next/navigation"; export default async function Page({ params, searchParams, }: { params: Promise<{ slug: string }>; searchParams: Promise<{ q?: string; page?: string }>; }) { const { slug } = await params; const { page } = await searchParams; const post = await getPost(slug); if (!post) notFound(); if (post.movedTo) permanentRedirect(`/posts/${post.movedTo}`); return <Article post={post} page={Number(page ?? 1)} />; }

redirect() throws, so it must come after every conditional decision and outside a try. In a Server Action it sends the redirect to the client as part of the action result; during a render it sends an HTTP 307 (or 308 with permanentRedirect).

Key Comparison Table

APIRuns inAvailable dataTriggers networkTypical use
<Link>Anyhref, prefetch, replace, scrollYes, on viewport entryNormal navigation
router.push / replaceClient onlyString or objectYesAfter an event or a check
router.refreshClient onlyCurrent routeYes, RSC payload onlyAfter a mutation without losing state
redirect()ServerAbsolute or relative pathFull route renderAuth gate, post-mutation
usePathnameClient onlyCurrent pathNoActive link styling
useSearchParamsClient onlyURLSearchParamsNoFilters, pagination
searchParams propServerPromise of the query objectn/aServer-side filtering and metadata
useParamsClient onlyDynamic segment valuesNoClient components inside a dynamic route
Navigation typePreserves client stateRe-fetches server dataAdds history entry
<Link> / router.pushYes, shared layoutsYes, changed segmentsYes
router.replaceYesYesNo
router.refreshYesYes, same URLNo
redirect()No, new renderYesDepends on status
Full page load (window.location)NoYes, whole documentYes

Practical Edge Cases & Deep Dives

1. The Suspense requirement for useSearchParams

A static page that calls useSearchParams() must be wrapped in <Suspense>, because the hook's value is only known at request time on the client. The build error names the component; the fix is to isolate the hook in a leaf client component:

tsx
// app/shop/page.tsx — stays static import { Suspense } from "react"; import { FilterBar } from "./filter-bar"; export default function Shop() { return ( <> <h1>Shop</h1> <Suspense fallback={<div className="h-10" />}> <FilterBar /> </Suspense> </> ); }

Wrapping the whole page also compiles, but then the entire page streams from the client boundary and you lose static HTML for the product grid.

2. Reading searchParams on the server for pagination

Server-side pagination should read searchParams in the page, not in a client hook, so the first paint already has page two's content and the canonical URL is correct:

tsx
export const revalidate = 300; export default async function Blog({ searchParams }: { searchParams: Promise<{ page?: string }> }) { const { page } = await searchParams; const current = Math.max(1, Number(page ?? 1)); const { posts, total } = await listPosts({ page: current, perPage: 20 }); return ( <> <PostGrid posts={posts} /> <Pager current={current} total={total} /> </> ); }

Reading searchParams makes the route dynamic — that is correct for a filtered list. If you want static pagination, generate /blog/page/[n] routes with generateStaticParams instead.

3. After a mutation: refresh versus revalidatePath

router.refresh() re-fetches the RSC payload for the current route and merges it without losing client state. revalidatePath on the server invalidates the cache so the next render is fresh. In a Server Action, revalidatePath runs before the framework's own refresh, so the action's return already shows new data — no router.refresh() needed. Calling both is harmless but redundant; calling only router.refresh() after a write that hit a cached fetch shows stale data.

4. Scroll behaviour and scroll={false}

<Link> restores scroll to the top on navigation and back to the remembered offset on history navigation. For filter panels and modals, scroll={false} keeps the viewport still. The pair that surprises people is router.push(url, { scroll: false }) — supported since Next.js 14 — and router.replace on a query-only change, which otherwise jumps the user to the top of a long list.

5. Prefetch cost and the "instant on hover" illusion

In production, <Link> prefetches the static part of the target route when it enters the viewport; dynamic routes prefetch only the loading state until hover. A product table with 200 rows therefore issues 200 prefetch requests on mount. Mitigations: prefetch={false} on rows, render the first 20 and paginate, or move the table to a client component with virtualization. Also note that prefetching does not cross an interception boundary differently — the intercepted variant is what gets prefetched when the link is inside the intercepting layout.

6. Query strings, encoding, and URLSearchParams

Building query strings by concatenation breaks the first time a value contains &, #, or a space. Use URLSearchParams and keep the existing parameters:

ts
"use client"; const params = useSearchParams(); const router = useRouter(); const pathname = usePathname(); function setFilter(key: string, value: string) { const next = new URLSearchParams(params.toString()); if (value) next.set(key, value); else next.delete(key); next.delete("page"); // filters reset pagination router.push(`${pathname}?${next.toString()}`); }

useSearchParams() returns a read-only snapshot; mutating it has no effect. And on the server, searchParams values are string | string[] | undefined — a repeated key arrives as an array, which Number() will happily turn into NaN.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Build error: missing suspense boundary with useSearchParamsHook used in a statically rendered route without SuspenseIsolate it in a client component under <Suspense>
Link click does nothinghref undefined at render (data not loaded)Guard render until the id exists, or use a disabled state
Page scrolls to top on filter changeDefault scroll behaviour on navigationscroll={false} on the link or router call
Data stale after a form submitOnly router.refresh() used, fetch cachedrevalidatePath / revalidateTag in the action
History grows on every keystrokepush in an input handlerreplace, plus debounce
Redirect never firesredirect() inside try/catch, or after a returnCall it last, outside the block
params.slug is a PromiseNext.js 15 async params in a client componentUse useParams(), or await params on the server

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.