You've been using Link for three lessons without looking inside it. It's time to do so, because much of the feeling of speed in a Next.js application depends on it: it prefetches the destination before the click, keeps the shared layouts and replaces only what changes.
In this lesson you'll understand what happens during a client-side navigation, control the history and scrolling, highlight the active section, build the guide's search form with next/form and learn to navigate from code, both in the browser with useRouter and on the server with redirect. The project's first client components will appear; here you'll use only what's essential, and 03-02 will explain them in depth.
- What Link does
Link renders an <a> element with a real href. It can be opened in another tab, search engines follow it and it works even if the JavaScript hasn't loaded. Once hydrated, it adds three things.
- Prefetching. When the link enters the viewport, or when the pointer hovers over it, it requests part of the destination in the background. This only happens in production: with
npm run devyou won't see any prefetching. - Client-side navigation. It intercepts the click, keeps the shared layouts and asks the server for the RSC Payload of whatever is missing, instead of a new document.
- Scroll and history management, so that the browser buttons work as expected.
<a href> |
<Link href> |
|
|---|---|---|
| Document | Downloaded in full | Kept |
| Shared layouts | Rebuilt | Stay |
| Client state | Lost | Kept |
| Prefetching | No | Yes |
Use <a> for other sites, for downloads and when you want a full load. You'll see a case later on.
1.1. What gets prefetched
The project has partialPrefetching: true, and that determines the answer. For each route, not for each link, Next.js prefetches an App Shell: its static, cached content that doesn't depend on the specific URL. Whatever depends on params, searchParams or uncached data arrives after the click.
Think of the guide: six cards link to six event pages, but they're all the same route, /events/[slug]. A single shell is prefetched and it serves all six. When you click any of them, the shell with "Loading the event…" appears immediately and the event page arrives afterwards.
sequenceDiagram
participant U as User
participant N as Browser
participant S as Server
N->>S: Prefetch of the /events/[slug] App Shell
S-->>N: Shell with the loading text
U->>N: Click on "Jazz Night"
N->>N: Shows the shell instantly
N->>S: Requests the content of /events/jazz-night
S-->>N: Event page
This explains why it mattered to move the waits down in the previous lessons. If the page awaited params outside a boundary, there would be no shell to prefetch.
The prefetch prop adjusts the behavior per link: false disables it (useful in huge lists) and true also requests the cached content that depends on the URL. When it's worth it is analyzed in 10-02; for now, leave it alone.
1.2. History and scrolling
| Prop | Default | Why change it |
|---|---|---|
href |
Required | A string or a { pathname, query } object |
replace |
false |
Replaces the current history entry instead of adding another one |
scroll |
true |
With false, Next.js doesn't change the scroll position |
prefetch |
null (automatic) |
Reduce or extend prefetching |
onNavigate |
— | Run something when navigating, or cancel with preventDefault() |
scroll={true} doesn't mean "always scroll to the top". Next.js keeps the position if the new page is already visible, and scrolls to its top if it isn't. If a fixed header covers the content, you fix it with the CSS property scroll-padding-top.
replace is appropriate when the intermediate step doesn't deserve a "back": switching tabs within an event page, or moving forward in a carousel. We don't use it in the guide's pagination, because going back to the previous page with the browser button is useful.
- The active link
The header doesn't show which section you're in. It lives in a layout, which doesn't know the current route, so you need a client component: these do re-render when you navigate. The usePathname hook returns the path, without the search params.
// components/nav-link.tsx
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
interface Props {
href: string
exact?: boolean
children: React.ReactNode
}
export function NavLink({ href, exact = false, children }: Props) {
const pathname = usePathname()
const active = pathname === href || (!exact && pathname.startsWith(`${href}/`))
return (
<Link
href={href}
aria-current={active ? 'page' : undefined}
className={active ? 'font-semibold underline' : ''}
>
{children}
</Link>
)
}'use client'on the first line declares that this module, and whatever it imports, also runs in the browser. That's the only way it can use hooks. The directive and its consequences are the subject of 03-02.startsWithwith the trailing slash prevents/eventsfrom being active on a hypothetical/events-archive.exactis for/dashboard, which would otherwise be active on all its subroutes.aria-current="page"conveys the same thing as the bold text to people using a screen reader.
2.1. usePathname needs Suspense too
On /events or /venues the route is known at build time. On /events/[slug] it isn't: Next.js prerenders the shell without knowing the slug, and usePathname suspends. Since the header is in the layout of those routes, the component has to go inside a <Suspense>; otherwise, the build fails.
The documentation recommends keeping the boundary small and making the fallback useful. Here that's easy: while it isn't known whether the link is active, the same link is shown without highlighting.
// components/header.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { NavLink } from '@/components/nav-link'
import { SITE_NAME } from '@/lib/site'
const SECTIONS = [
{ href: '/events', text: 'Events' },
{ href: '/venues', text: 'Venues' },
]
export function Header() {
return (
<header className="border-b border-slate-200 bg-white">
<div className="mx-auto flex max-w-5xl items-center justify-between px-4 py-4">
<Link href="/" className="text-xl font-bold text-teal-800">
{SITE_NAME}
</Link>
<nav aria-label="Main" className="flex gap-6">
{SECTIONS.map(({ href, text }) => (
<Suspense key={href} fallback={<Link href={href}>{text}</Link>}>
<NavLink href={href}>{text}</NavLink>
</Suspense>
))}
</nav>
</div>
</header>
)
}Header is still a Server Component: only the link crosses over to the client. Apply the same thing to the dashboard menu, where there will be dynamic routes later on:
// app/(dashboard)/dashboard/_components/dashboard-menu.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { NavLink } from '@/components/nav-link'
const ITEMS = [
{ href: '/dashboard', text: 'Overview', exact: true },
{ href: '/dashboard/events', text: 'My events', exact: false },
]
export function DashboardMenu() {
return (
<nav aria-label="Dashboard" className="flex flex-col gap-2">
{ITEMS.map(({ href, text, exact }) => (
<Suspense key={href} fallback={<Link href={href}>{text}</Link>}>
<NavLink href={href} exact={exact}>
{text}
</NavLink>
</Suspense>
))}
</nav>
)
}In development, an oversight can go unnoticed, because routes are rendered on demand. npm run build is the reliable check.
- The search form: next/form
Category links don't scale to three criteria. A search form is a form whose submission leads to a URL, and HTML has always handled that with method="GET": the fields become search params. The only drawback of the native form is that it reloads the document.
The Form component from next/form fixes exactly that. With a string action it behaves like a GET form, but it prefetches the destination and performs a client-side navigation. Without JavaScript it still works like the native one.
// app/(public)/events/_components/filter-form.tsx
import Form from 'next/form'
import Link from 'next/link'
import { listDistricts } from '@/lib/data/venues'
import { createEventsUrl, normalizeFilters, type RawSearchParams } from '@/lib/filters'
import { CATEGORY_LABELS } from '@/lib/format'
import { CATEGORIES } from '@/lib/types'
interface Props {
searchParams: Promise<RawSearchParams>
}
export async function FilterForm({ searchParams }: Props) {
const filters = normalizeFilters(await searchParams)
const districts = await listDistricts()
const formKey = createEventsUrl({ ...filters, page: 1 })
return (
<Form action="/events" role="search" className="mb-6">
<div key={formKey} className="flex flex-wrap items-end gap-4">
<label className="flex flex-col">
Search
<input name="q" type="search" defaultValue={filters.q} className="border px-2" />
</label>
<label className="flex flex-col">
Category
<select name="category" defaultValue={filters.category} className="border px-2">
<option value="">All</option>
{CATEGORIES.map((category) => (
<option key={category} value={category}>
{CATEGORY_LABELS[category]}
</option>
))}
</select>
</label>
<label className="flex flex-col">
District
<select name="district" defaultValue={filters.district} className="border px-2">
<option value="">All</option>
{districts.map((district) => (
<option key={district}>{district}</option>
))}
</select>
</label>
<button type="submit" className="rounded bg-teal-800 px-4 py-1 text-white">
Filter
</button>
<Link href="/events">Clear filters</Link>
</div>
</Form>
)
}- The field names are the URL's names.
name="category"produces?category=…, whichnormalizeFiltersalready knows how to read. Empty fields are sent as?q=&district=; it treats those as missing too. - There's no
pagefield, so any new filter starts on the first page. defaultValue, notvalue. The fields aren't controlled by React: the browser keeps what's typed and the server only provides the initial value.key={formKey}on the container.defaultValueis only applied when the field is created, so "Clear filters" would change the URL and leave the fields as they were. When thekeychanges, React creates them again with the values from the URL. It goes on an inner<div>becauseFormdoesn't accept akeywhen itsactionis a string.- It's an asynchronous Server Component.
Formis a client component, but it can be used inside a server one.
The downside of the key is that the field that had focus is recreated and loses it after filtering. That's an acceptable cost here; in a search that updated as you type, it wouldn't be.
In the page, replace CategoryFilter with the form, in its own boundary, and delete category-filter.tsx:
// app/(public)/events/page.tsx (EventsPage)
export default function EventsPage({ searchParams }: Props) {
return (
<>
<h1 className="mb-6 text-3xl font-bold">Event guide</h1>
<Suspense fallback={<p className="mb-6">Loading filters…</p>}>
<FilterForm searchParams={searchParams} />
</Suspense>
<Suspense fallback={<p>Loading the guide…</p>}>
<EventResults searchParams={searchParams} />
</Suspense>
</>
)
}The same promise is passed to both components. There's no duplicated work: it's a value that's already on its way, and each one awaits it on its own.
- Navigating from code with useRouter
Sometimes there's no link or form: the navigation is the consequence of something else. That's what useRouter is for, in a client component. It's imported from next/navigation; the one in next/router belongs to the Pages Router.
| Method | Effect |
|---|---|
push(href, options) |
Navigates and adds an entry to the history |
replace(href, options) |
Navigates and replaces the current one |
back() and forward() |
Move through the history |
refresh() |
Requests the route from the server again, without losing client state |
prefetch(href) |
Prefetches manually |
push and replace accept { scroll: false }. As an example, a select that filters on change, with no button. It needs to keep the other parameters, and to read them on the client there's useSearchParams:
// Example: a client-side alternative for the district (we won't use it)
'use client'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
export function DistrictSelect({ districts }: { districts: string[] }) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
function handleChange(district: string) {
const next = new URLSearchParams(searchParams.toString())
if (district) next.set('district', district)
else next.delete('district')
next.delete('page')
router.replace(`${pathname}?${next}`, { scroll: false })
}
return (
<select
aria-label="District"
value={searchParams.get('district') ?? ''}
onChange={(event) => handleChange(event.target.value)}
>
<option value="">All</option>
{districts.map((district) => (
<option key={district}>{district}</option>
))}
</select>
)
}useSearchParams returns a read-only version of URLSearchParams; to modify it, you copy it. And, unlike usePathname, search params are never known at build time: their component needs a <Suspense> on any prerendered route.
| Tool | Where | Use it to |
|---|---|---|
searchParams prop |
Page (server) | Filter or paginate the query |
useSearchParams |
Client component | React to the URL in the browser |
window.location.search |
Event handler | Read it at a specific moment, without subscribing |
Why do we stick with Form? It doesn't ship any of our own JavaScript, it works before hydrating and it applies all the criteria at once. useRouter is reserved for what a link or a form can't express, such as closing a modal (02-05).
4.1. Two precautions
- Don't pass an address that comes from the user to
pushorreplacewithout checking it. Ajavascript:URL would run in your page. It's a typical risk with parameters like?returnTo=…; accept only internal routes. refresh()isn't a "refresh everything" button. It repeats the request for the route, but it doesn't invalidate what's cached on the server. After modifying data, you use the functions from 05-04.
- Redirecting from the server
When the decision is made while rendering on the server, you use redirect, also from next/navigation. Internally it throws a special error that stops the component, so you don't need a return.
The guide offers a good case. ?page=99 shows the last page, but with an address that doesn't match it. Let's send the user to the right one:
// app/(public)/events/page.tsx (inside EventResults)
const filters = normalizeFilters(await searchParams)
const { events, total, page, totalPages } = await listEvents(filters)
if (filters.page !== page) {
redirect(createEventsUrl({ ...filters, page }))
}Add the redirect import. There's no risk of a loop: on the second visit the requested page matches the one returned.
For permanent moves there's permanentRedirect. If a venue changed its slug, for example, you'd call it with the new address before treating the venue as nonexistent.
redirect |
permanentRedirect |
|
|---|---|---|
| Meaning | Temporary | Permanent |
| HTTP status, if the response hasn't started | 307 | 308 |
| If it's already streaming | A meta tag that redirects in the browser |
Same |
| In a Server Action, with JavaScript | Client-side navigation | Same |
The third row is our case. EventResults resolves after the shell has been sent, and with it the 200 status. The redirect works for the user, but it isn't a 307. When the HTTP status matters, the redirect has to be decided before rendering: in next.config.ts or in the proxy (07-02).
And remember: since it throws an error, a redirect inside a try gets caught by your catch. Always call it outside.
- Showing that navigation is in progress
When you change pages in the guide, the route is the same and only the parameters change. React keeps the previous list visible until the new one arrives, and on a slow network it looks as if the click did nothing. The useLinkStatus hook tells you whether its link has a pending navigation. It must be used in a component placed inside the Link:
// components/link-indicator.tsx
'use client'
import { useLinkStatus } from 'next/link'
export function LinkIndicator() {
const { pending } = useLinkStatus()
return (
<span
aria-hidden
className={`ml-1 inline-block transition-opacity delay-100 ${
pending ? 'opacity-100' : 'opacity-0'
}`}
>
⋯
</span>
)
}// components/pagination.tsx (both links)
<Link href={createHref(page - 1)}>
Previous
<LinkIndicator />
</Link>
<Link href={createHref(page + 1)}>
Next
<LinkIndicator />
</Link>The indicator always takes up its space and only changes its opacity, so it doesn't shift the text. The 100 ms delay avoids a flicker when the response is fast.
Think of it as a complement. If the destination has a prefetched shell, the navigation is immediate and the pending state is skipped. The first priority is for routes to have good loading states, which is what comes next.
Common Mistakes and Tips
- Using
<a>for internal links. Every click reloads the document and loses state. - Using
useRouterin a button that could be aLink. You lose prefetching, opening in another tab and accessibility. - Importing
useRouterfromnext/router. Inapp/it's imported fromnext/navigation. - Putting
'use client'on the whole header for the sake of an active link. Isolate the hook in a small component. - Forgetting the
<Suspense>arounduseSearchParams, or aroundusePathnamein layouts with dynamic routes below them. - Looking for prefetching in development. Check it with
npm run buildandnpm run start. - Calling
redirectinside atry. Thecatchswallows it. - Calling
redirectin an event handler. It only works while rendering or on the server; on a click, you useuseRouter.
Exercises
Exercise 1: choosing the tool
State what you'd use and why: (1) a card's title leads to its event page; (2) a link to an external venue's website; (3) a "Back" button that returns to wherever the user was; (4) /dashboard must send the user to /sign-in if there's no session; (5) a search box in the header that opens /events?q=….
Solution
Link. It's an ordinary link.<a>. It's another site: there's nothing to prefetch and no layouts to keep.useRouter().back()in a client component, because the destination depends on the history. If the destination were fixed, aLink.redirecton the server, next to the session check (module 8).Formwithaction="/events"and aname="q"field. It works even without JavaScript.
Exercise 2: a search box on the home page
Add a text search box to the home page that leads to the guide. Does it need a <Suspense>? What about 'use client'?
Solution
// app/(public)/page.tsx (import Form from 'next/form')
<Form action="/events" role="search" className="mt-4 flex gap-2">
<input
name="q"
type="search"
aria-label="Search events"
placeholder="Jazz, pottery…"
className="border px-2"
/>
<button type="submit">Search</button>
</Form>Neither. The form doesn't read the URL or fetch data, so it's part of the static shell. Form is a client component, but it already comes with its own directive: using it doesn't turn the page into a client component.
Exercise 3: the failing build
A teammate adds this component to PublicLayout. Everything works in development, but npm run build fails. Explain why and fix it without losing the header from the shell.
'use client'
import { useSearchParams } from 'next/navigation'
export function CampaignNotice() {
const source = useSearchParams().get('source')
return source === 'poster' ? <p>Thanks for scanning the poster.</p> : null
}Solution
Search params don't exist during prerendering, and the component suspends outside any boundary on every public route. In development, routes are generated on demand, so the oversight may go unnoticed. You wrap only the notice:
<Header />
<Suspense fallback={null}>
<CampaignNotice />
</Suspense>
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">{children}</main>A null fallback is acceptable because most visits won't see the notice. Wrapping Header and children as well would have left the shell empty.
Conclusion
Link is a real link that prefetches the destination's shell and changes only what's necessary. Form does the same for search forms. Navigation hooks are reserved for small client components, with their <Suspense> when they read a URL that isn't known at build time, and redirect handles the server's decisions, with the caveat that a response that has already started can't change its HTTP status.
That caveat comes up again right away. At the moment, a nonexistent slug shows a paragraph, a data failure isn't handled and the loading texts are minimal. In the next lesson, Loading States, Errors and Not Found Pages, you'll complete those three cases.
