Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 50 ยท Params and Search Params

Search Params and useSearchParams

Read, update and validate the query string with useSearchParams: functional updates, repeated keys for arrays, defaults, and filters that live in the URL.

A URL has more parts than a path. After the ? comes the query string: /products?category=books&tag=travel&tag=paper. Unlike a path param, a search param does not change which route matches. /products and /products?category=books render the same route, and the component decides what the query means. That makes search params the right home for optional, shareable view state: filters, search text, sort order, page numbers.

The router gives you useSearchParams, a hook that reads the query string and returns a function to update it. It is built on the browser's URLSearchParams, so most of this lesson is about using that object well. We build on Dynamic Segments and useParams: path params say which thing, search params say how to look at it.

Reading search params

useSearchParams returns a pair, like useState: the current params and a setter.

JSX
import { useSearchParams } from "react-router";

function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();

  const category = searchParams.get("category"); // string | null
  const tags = searchParams.getAll("tag");        // string[]
  const isSale = searchParams.has("sale");        // boolean

  // ...
}

The first element is a standard URLSearchParams object, with the methods you may know from the browser:

Method What it does
get(key) First value for the key, or null if absent
getAll(key) Every value for a repeated key, as an array
has(key) true if the key is present
set(key, value) Replaces all values of the key with one
append(key, value) Adds another value without removing existing ones
delete(key) Removes the key completely
toString() Gives the encoded text, without the leading ?

Two details matter. Everything is a string: ?page=2 gives "2", and a missing key gives null, not undefined. And a present-but-empty key (?q=) gives the empty string, which is different from null.

flowchart LR
  U["/products?category=books&tag=a#top"] --> P["pathname<br/>/products<br/>(picks the route)"]
  U --> S["search<br/>?category=books&tag=a<br/>(useSearchParams)"]
  U --> H["hash<br/>#top"]

Only the pathname takes part in route matching; the search and hash ride along.

Updating search params

The setter works like navigate, but only for the query part of the URL. You can pass a new set of params in several forms: a string, an object, a URLSearchParams, or an array of pairs.

JSX
setSearchParams({ category: "books", sort: "name" });  // -> ?category=books&sort=name

Notice that this call replaces the whole query string. Any other key that was there is gone. To change one param and keep the rest, use the functional form, which receives the current params:

JSX
setSearchParams((prev) => {
  const next = new URLSearchParams(prev);
  next.set("category", "books");
  next.delete("page"); // a new filter should go back to page 1
  return next;
});

Copying prev into a new URLSearchParams is a good habit: you never mutate the object that React Router handed you.

Three behaviors to know:

  • Each update adds a history entry by default, like navigate. Pressing Back then undoes the change. That is right for a deliberate step such as going to page 2, but wrong for every keystroke in a search box. Pass { replace: true } as the second argument to overwrite the current entry instead: setSearchParams(next, { replace: true }).
  • Functional updates are not queued. Unlike setState(prev => ...), two calls in the same event handler both receive the params from the same render, so the second call overwrites the first. If you need two changes, make them in one call.
  • Updates navigate, so components re-render. Everything that reads the query string reflects the new value on the next render. There is no separate "state" to keep in sync.

A relative link can also change the query without JavaScript: <Link to="?category=books">Books</Link> keeps the current path and replaces the query. A form can too: <Form method="get"> serializes its fields into the query string (see Actions and Form).

Arrays: repeat the key

A query string has no array syntax. The convention that URLSearchParams supports directly is to repeat the key: ?tag=travel&tag=paper. Read it with getAll, add with append, and remove one value by rebuilding the list.

JSX
function toggleTag(tag) {
  setSearchParams((prev) => {
    const next = new URLSearchParams(prev);
    const tags = next.getAll("tag");
    next.delete("tag");
    const updated = tags.includes(tag) ? tags.filter((t) => t !== tag) : [...tags, tag];
    updated.forEach((t) => next.append("tag", t));
    return next;
  }, { replace: true });
}

createSearchParams from React Router builds a URLSearchParams from an object and expands array values into repeated keys: createSearchParams({ tag: ["travel", "paper"] }) is tag=travel&tag=paper. A comma-separated value (?tags=travel,paper) also works and gives shorter URLs, but then you split the string yourself and must make sure no tag contains a comma.

A filter list driven by the URL

Here is a complete example. The product list has a text search, a category, tag toggles and a sort order. Nothing is stored in useState: every control reads from the query string and writes to it. Look at the "URL" line while you click.

A product filter that lives in the URL

Click "books" and then the "paper" tag: the URL becomes /?category=books&tag=paper and only two items remain. Click "paper" again and the tag disappears from the URL. A default value (category "all", sort "name-asc") is never written, which keeps shared links short: the code treats a missing key as the default.

Three habits in this component are worth copying:

  • Whitelist values. sort is accepted only if it is a known value; anything else falls back to the default. Never trust the query string to contain what your UI offers.
  • Delete instead of storing empty values. update removes a key when the new value is empty or null.
  • Use replace for typing. Each keystroke would otherwise add a history entry.

Parsing numbers and keeping pages in range

A page number is the classic case where a string needs care. A visitor can edit the URL to ?page=abc, ?page=-4 or ?page=999. Write a small parser that turns anything into a valid page and use it everywhere.

Pagination with a safe page parser

Press "Next" twice, then "+1 twice (two calls)": the page moves forward by one, not two, because both calls start from the same searchParams. "+2 (one call)" does move by two. The three hand-edited links all land on a valid page, and page 1 has no page key at all.

flowchart LR
  A["User clicks a control"] --> B["setSearchParams(...)"]
  B --> C["URL changes<br/>(push or replace)"]
  C --> D["useSearchParams returns<br/>new values"]
  D --> E["Component re-renders<br/>with the filtered view"]
  E --> A

The URL is the state: every change goes through it and comes back as render input.

When to use search params

Use them for state that is optional, small and worth sharing or bookmarking: filters, search text, sort order, page, selected tab. Do not use them for secrets (URLs end up in logs, history and referrer headers), for large data, or for state that is meaningless on its own (a half-typed form field). The next lesson, Putting UI State in the URL, builds on this with tabs, modals and debounced inputs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A URL is /products?page=2. What does searchParams.get("missing") return?

    URLSearchParams.get returns null for an absent key. Present-but-empty keys (?q=) give an empty string, which is a different case.
  2. 2. The URL is /?category=books&sort=name. You call setSearchParams({ page: "2" }). What is the new query string?

    Passing a plain value replaces the entire query string. To keep the other keys, use the functional form and copy the previous params.
  3. 3. Why pass { replace: true } when updating the query on every keystroke of a search box?

    By default each update pushes a history entry. Replacing the current entry keeps history clean for continuous input; the URL still updates and the view stays shareable.
  4. 4. You call setSearchParams(bump) twice in one click handler, where bump adds 1 to the current page. The page was 1. What is the page afterwards?

    Functional updates are not queued like useState updates. Both calls start from the params of the same render, so each computes page 2, and the result is 2.
  5. 5. How do you represent a list of tags in a query string with URLSearchParams?

    Repeated keys are the convention URLSearchParams supports directly. Comma-separated values also work, but you then split the string yourself.

Summary

  • Search params live after the ?, do not affect route matching, and are read with useSearchParams, which returns a URLSearchParams plus a setter.
  • Values are strings (or null when absent); parse and clamp numbers, and whitelist known values.
  • A plain value passed to the setter replaces the whole query; use the functional form to change one key and keep the rest.
  • Updates push a history entry by default; use { replace: true } for continuous input, and do not rely on functional updates being queued.
  • Arrays use repeated keys (getAll, append); defaults are best left out of the URL.
  • Put optional, shareable view state in the URL, and keep secrets out of it.

Next: Putting UI State in the URL