Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 20 min · revision 3

Navigation and Keeping State in the URL

Read search params on the server, build links and pagination that carry state, and wire a filter control that works without JavaScript and gets faster with it — so every view of the catalog has an address you can reload or share.

Contentsand lesson path

What you will learn

  • Navigate with Link and the router, read route params and search params, and keep filter, sort and pagination state in the URL.

Prerequisites: React Components & State

01. Why the URL is the state

A filtered, sorted, paginated view is a result the learner may want to keep: reload it, send it to a colleague, bookmark it, or go back to it after following a detail link. If that view lives only in component state, the address bar cannot describe it — every one of those actions loses it. If it lives in the query string, the URL is the state, and the page can be rebuilt from the address alone.

That single decision shapes the code: the server reads searchParams to know what to render, links carry the state forward, and controls update the URL instead of updating variables. Navigation in Next.js is built on top of this. Clicking a Link updates the URL in the browser's history (a plain anchor would too, but with a full document load), then asks the server only for the parts of the page that changed, while shared layouts stay mounted and interactive. Get the URL right and both paths — a full reload and an in-app click — lead to the same view.

The app from the previous lesson already links products; this lesson adds sorting, categories and pagination to /catalog, and finishes with a filter control that degrades gracefully. All of it ran on Next.js 16.4.6 with React 19.3.0.

02. Step 1: read search params on the server

TypeScript · app/catalog/page.tsx (excerpt)
export const instant = false;

function first(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}

export default async function CatalogPage(props: PageProps<'/catalog'>) {
  const params = await props.searchParams;
  const category = first(params.category);
  const sort = first(params.sort) ?? 'title';
  const requested = Number.parseInt(first(params.page) ?? '1', 10);
  const products = getProducts(category, sort);
  const pageCount = Math.max(1, Math.ceil(products.length / PAGE_SIZE));
  const page = Math.min(Math.max(1, requested || 1), pageCount);
  const visible = products.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

A page receives searchParams as a prop — a Promise in current Next.js versions, so the server awaits it — and the query string drives every decision: filter, sort, page. The code is defensive on purpose. A parameter can arrive as string, as an array of strings when a name is repeated, or be absent; first() narrows that union. A page number out of range is clamped instead of slicing an empty list. The instant = false export at the top is needed because cacheComponents is on: a page that reads searchParams with no Suspense boundary above it fails the static-shell check that next build runs, and instant = false switches that check off so the route may block until its data is ready. The loading lesson shows the other way out, a loading.tsx fallback that lets the page stream instead.

Terminal
$ curl -s 'http://localhost:3131/catalog?sort=price-asc' \
  | grep -oE '<a href="/catalog/[a-z-]+">[A-Za-z ]*'
$ curl -s 'http://localhost:3131/catalog?category=grinders&sort=price-desc' \
  | grep -oE '<a href="/catalog/[a-z-]+">[A-Za-z ]*'
Expected output
<a href="/catalog/french-press">French press
<a href="/catalog/stovetop-espresso">Stovetop espresso maker
<a href="/catalog/workshop-grinder">Workshop grinder
<a href="/catalog/hand-grinder">Hand grinder

Two different query strings, two different lists, straight from the server: £24 before £32, then £129 before £45. Nothing here is client-side — a fresh HTML document answers each address, which is exactly why the address is enough to rebuild the view.

04. Step 3: a filter control that degrades gracefully

TypeScript · app/catalog/filter-bar.tsx
'use client';

import { useRouter, useSearchParams } from 'next/navigation';

const SORTS = [
  { value: 'title', label: 'Title (A to Z)' },
  { value: 'price-asc', label: 'Price: low to high' },
  { value: 'price-desc', label: 'Price: high to low' },
];

export function FilterBar() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const category = searchParams.get('category');

  return (
    <form action="/catalog" method="get">
      {category && <input type="hidden" name="category" value={category} />}
      <label htmlFor="sort">Sort by</label>
      <select
        id="sort"
        name="sort"
        defaultValue={searchParams.get('sort') ?? 'title'}
        onChange={(event) => {
          const next = new URLSearchParams(searchParams.toString());
          next.set('sort', event.target.value);
          next.delete('page');
          router.replace(`/catalog?${next.toString()}`);
        }}
      >
        {SORTS.map((sort) => (
          <option key={sort.value} value={sort.value}>
            {sort.label}
          </option>
        ))}
      </select>
      <button type="submit">Apply</button>
    </form>
  );
}

Read the form before the JavaScript. It is a plain HTML form that submits GET to /catalog, so the browser turns the select's name="sort" into a query parameter and navigates — no framework involved. A GET form replaces the whole query string with its own fields, so the hidden category input carries the current filter along; without it, pressing Apply on /catalog?category=grinders with JavaScript off would land on /catalog?sort=… and lose the category. That is the floor every learner gets. The enhancement is the onChange handler: once the component hydrates, changing the option navigates immediately with router.replace, building the next URL from searchParams.toString() so the category survives, and deleting page so a new sort starts from page 1.

Three API details worth remembering. useSearchParams is a Client Component hook — the server reads searchParams from props, as in step 1. The object it returns is read-only: copy it (new URLSearchParams(searchParams.toString())), then set and delete on the copy. And replace rather than push keeps the back button meaningful: choosing three sorts in a row should not cost three back presses to escape.

Terminal
$ curl -s http://localhost:3131/catalog | grep -oE \
  '<form[^>]*>|<option[^>]*>[^<]*</option>|<button[^>]*>[^<]*</button>'
Expected output
<form action="/catalog" method="get">
<option value="title" selected="">Title (A to Z)</option>
<option value="price-asc">Price: low to high</option>
<option value="price-desc">Price: high to low</option>
<button type="submit">Apply</button>

Even a Client Component server-renders its first pass: curl sees the full form with defaultValue already reflecting the current URL (selected on the active option). After hydration the same markup also responds to onChange. The address bar, the rendered list and the select stay in step because all three read from the same source — the URL.

05. What usually goes wrong

06. Check your understanding

Practice check · 3 questions

Navigation and URL state

Think through the FilterBar and the pagination links.

Q1. The FilterBar navigates with router.replace, not router.push. After choosing three sorts in a row, what does one press of the back button do?
Q2. With JavaScript disabled, the learner picks a different option and presses Apply. What happens?
Q3. A colleague moves the sort choice into useState and calls router.refresh() after each change. What is lost?
Practice only: not graded, not saved, not evidence.

07. Apply it

Add a price-band filter to the running catalog:

  1. Accept ?max= (a number) in the page, and filter products with it.
  2. Extend catalogHref so every link keeps max alongside category and sort.
  3. Add a number input to the FilterBar form. Check both paths: submit the form with JavaScript off, then wire onChange to router.replace, remembering to drop page.
  4. Reload each filtered URL, copy one into a new tab, and confirm the list is identical. If anything differs, the state has leaked out of the URL.

For contrast on where view state belongs, compare with /skills/frontend-state-management: component state for ephemeral UI, the URL for anything shareable.

08. Review prompt

Without looking back: how does a Server Component page read the query string, and what shape can each value take? Why does the pagination helper start from an empty URLSearchParams instead of the current string? What does a GET form give you before any JavaScript loads, and what do useSearchParams, the copy-then-set rule, and router.replace each add after it?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check