Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 72 ยท Routing

Search Params and Navigation Hooks

Read the query string on the server with the searchParams prop and in the browser with useSearchParams, then build a shareable filter UI with the navigation hooks.

Open any online shop and filter the shoes by price. The address bar changes to something like /products?category=shoes&sort=price. Copy that link, send it to a friend, and they see the same filtered list. The state of the page lives in the URL, which is exactly what you want for filters, sorting, pagination and search boxes: links are shareable, the Back button works, and a refresh does not lose anything.

Next.js gives you several ways to read the URL, and choosing the right one depends on where your code runs. On the server, the page receives a searchParams prop. In the browser, hooks from next/navigation (useSearchParams, useParams, usePathname, useSelectedLayoutSegment) tell a client component where it is. This lesson explains each one and builds a filter UI that uses both sides together. You should know Dynamic Routes and Linking and Navigation first.

Real framework or stand-in? The tsx snippets are real Next.js and read-only. The live examples are React stand-ins with a small in-memory router that has its own useSearchParams, useParams and useSelectedLayoutSegment. The server page is imitated by a plain function that receives a searchParams object. The sandbox cannot use the real URL bar, so the stand-in shows the URL as text.

Where does the code run?

Server page Gets a searchParams prop (a promise).
Client component Calls useSearchParams().
Layout Never gets searchParams. Use hooks inside it.
1 / 2

The searchParams prop (server)

A page.tsx receives searchParams next to params. Like params, it is a promise in Next.js 15 and 16. Its values are strings, or arrays of strings when a key is repeated (?tag=a&tag=b), or undefined when missing:

TSX
// app/products/page.tsx (read-only)
import { getProducts } from '@/lib/products';

type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>;

export default async function ProductsPage({
  searchParams,
}: {
  searchParams: SearchParams;
}) {
  const { category, sort = 'name', page = '1' } = await searchParams;

  const products = await getProducts({
    category: typeof category === 'string' ? category : undefined,
    sort: sort === 'price' ? 'price' : 'name',
    page: Math.max(1, Number(page) || 1),
  });

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name}: ${product.price}
        </li>
      ))}
    </ul>
  );
}

Three points matter here:

  • Validate everything. The query string is typed by the visitor. Check types (string versus an array), allow-list values (sort can only be 'name' or 'price') and convert numbers defensively.
  • Reading searchParams makes the page dynamic. The result depends on the request, so Next.js cannot prepare the page at build time. See Static vs Dynamic Rendering. A filter page being dynamic is normal; just know it is a cost.
  • Only pages receive it. Layouts do not get searchParams. A layout is shared between many pages and is not re-rendered when only the query string changes, so it could show stale data. If a layout needs the query, read it in a client component with the hook below.

Pagination, sorting and filters are all server-side reads of this prop. The server decides which rows to fetch and sends back HTML, so the browser downloads no filtering code at all.

useSearchParams (client)

An input box lives in a client component, so it cannot await a promise prop. It calls useSearchParams() instead, which returns a read-only URLSearchParams-like object:

TSX
// app/products/_components/sort-select.tsx (read-only)
'use client';

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

export function SortSelect() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  function changeSort(value: string) {
    const next = new URLSearchParams(searchParams.toString());
    next.set('sort', value);
    next.delete('page'); // a new sort starts on page 1
    router.replace(`${pathname}?${next.toString()}`);
  }

  return (
    <select value={searchParams.get('sort') ?? 'name'} onChange={(e) => changeSort(e.target.value)}>
      <option value="name">Name</option>
      <option value="price">Price</option>
    </select>
  );
}

The pattern has four steps, and it is worth memorizing:

  1. Copy the current params into a new URLSearchParams (the hook's value is read-only).
  2. Change the keys you care about (set, delete, append).
  3. Reset anything that depends on the old state, such as page.
  4. Navigate to pathname + '?' + params, which re-runs the server page with the new query.

Choose replace for changes that should not clutter history (typing in a search box), and push when each change is a step the visitor may want to go back to (clicking a page number). A text input should also be debounced, so you do not navigate on every keystroke; the stand-in below skips that to keep the code short.

There is one build-time rule to know. When a route is statically rendered, a component that calls useSearchParams() opts that part of the page into client-side rendering, so Next.js asks you to wrap it in a <Suspense> boundary. Without it, the build fails with a "missing Suspense boundary" error, because the query string does not exist at build time.

TSX
// app/products/page.tsx (read-only)
import { Suspense } from 'react';
import { SortSelect } from './_components/sort-select';

export default function Page() {
  return (
    <Suspense fallback={<p>Loading filters...</p>}>
      <SortSelect />
    </Suspense>
  );
}

On a page that is already dynamic (it awaits searchParams, for example) the boundary is not required, but it does no harm.

A filter UI you can run

The stand-in below has the two halves. ProductsPage is a plain function that receives a parsed searchParams object, like the real server page, and returns the filtered list. Filters is the client component: it reads useSearchParams(), copies it, changes one key and calls router.replace. Press "Next page" to reach page 2 of the full list, then pick a category or change the sort: the page key disappears from the URL, because the filter code deletes it. The page function also clamps an out-of-range page to the last page, which is what a real page should do with a hand-edited URL. The URL line at the top is what the address bar would show.

Filters that live in the URL

Notice the division of work. Filters never touches the product list; it only edits the URL. ProductsPage never reads an input; it only reads searchParams. That is exactly the shape you want in Next.js: the URL is the single source of truth, and both halves follow it.

useParams and useSelectedLayoutSegment

Two more hooks answer "where am I?" without the query string.

useParams() returns the values of the dynamic segments of the current route, as an object. It is the client-side counterpart of the params prop, with no promise to unwrap:

TSX
// app/shop/[category]/[id]/buy-button.tsx (read-only)
'use client';

import { useParams } from 'next/navigation';

export function BuyButton() {
  const { category, id } = useParams<{ category: string; id: string }>();
  return <button>Buy {category} #{id}</button>;
}

A catch-all segment (see Catch-All Routes) is returned as an array of strings.

useSelectedLayoutSegment() is made for layouts. Called inside a layout, it returns the name of the active child segment one level below that layout, or null when there is none. useSelectedLayoutSegments() returns all the active segments below the layout as an array. Inside app/shop/layout.tsx at /shop/shoes/42, the first returns 'shoes' and the second returns ['shoes', '42']. This is the cleanest way to highlight a tab bar or a sidebar item, because the layout does not need to know the full path or to parse it by hand:

TSX
// app/shop/_components/category-tabs.tsx (read-only)
'use client';

import Link from 'next/link';
import { useSelectedLayoutSegment } from 'next/navigation';

export function CategoryTabs() {
  const segment = useSelectedLayoutSegment(); // 'shoes', 'hats', or null
  return (
    <nav>
      <Link href="/shop/shoes" aria-current={segment === 'shoes' ? 'page' : undefined}>Shoes</Link>
      <Link href="/shop/hats" aria-current={segment === 'hats' ? 'page' : undefined}>Hats</Link>
    </nav>
  );
}

It also accepts an optional parallel-routes key for slots. The next stand-in imitates all three hooks for a layout at /shop. Click the links and compare what each hook returns. The stand-in matches the pattern /shop/[category]/[id] by position, because it has no real route table.

useParams and useSelectedLayoutSegment side by side

At /shop the segment is null; at /shop/shoes it is "shoes"; at /shop/shoes/42 it is still "shoes" (the first segment below the layout), while the segments array holds both shoes and 42. That is why tab bars use the singular hook and breadcrumbs use the plural one.

Choosing the right tool

You want to Use
Filter, sort or paginate with server data searchParams prop in page.tsx
Read or change the query in an input, tab or button useSearchParams + useRouter in a client component
Read a dynamic value in a client component useParams
Highlight the active tab or sidebar item in a layout useSelectedLayoutSegment
Know the current path usePathname

Keep UI state that should survive a reload or be shared (filters, sorting, the open tab) in the URL. Keep throwaway state (a dropdown being open) in React state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which component receives the searchParams prop in the App Router?

    Only pages get searchParams (and params). A layout is shared across pages and does not re-render for query-only changes, so it does not receive the query string. Client components use useSearchParams.
  2. 2. Why do you wrap a component that calls useSearchParams() in a Suspense boundary on a statically rendered route?

    Without a boundary, the build fails with a missing Suspense boundary error, because the part of the page that depends on the query string cannot be prerendered.
  3. 3. What is the correct way to change one query key from a client component?

    The hook's value is read-only. You build a new URLSearchParams, change it, and navigate to the new URL so the server page re-runs with the new query.
  4. 4. Inside app/shop/layout.tsx, the URL is /shop/shoes/42. What do useSelectedLayoutSegment() and useSelectedLayoutSegments() return?

    They look at the segments below the layout where they are called. The singular hook returns the first one, the plural hook returns all of them.
  5. 5. A visitor types in a search box on every keystroke. Which navigation call is the better default, and why?

    replace swaps the current history entry. Combine it with debouncing so typing does not trigger a request for every letter.

Summary

  • Keep filters, sorting, pagination and tabs in the URL: shareable, Back-friendly and refresh-safe.
  • A server page.tsx reads searchParams (a promise in 15 and 16); values can be a string, an array or undefined, so validate them. Reading it makes the page dynamic, and layouts never receive it.
  • A client component reads the query with useSearchParams, copies it into a new URLSearchParams, edits the copy and navigates with router.replace or push. Reset page when a filter changes.
  • Wrap useSearchParams users in <Suspense> on static routes.
  • useParams gives dynamic segment values on the client; useSelectedLayoutSegment(s) tells a layout which child route is active; usePathname gives the path.

Next: Parallel and Intercepting Routes