Sub topic 8
Reading and updating the query string
The query string is the part of a URL after the ?, such as /products?sort=price&page=2. This chapter shows how to read it, update it, and keep it consistent with your UI. It assumes you can define routes with createBrowserRouter, render links, and read path params with useParams.
Why the query string is state
Path segments identify a resource, such as /products/42. Query parameters describe how to view a resource or a list, such as its sort order, filter, page number, or search text.
Putting that view state in the URL has practical benefits:
- A user can copy the link and send it to someone, who sees the same view.
- The back and forward buttons step through earlier views.
- A reload keeps the view, which
useStatecannot do.
React Router treats the query string as a separate part of the location. A route's path never includes it, so /products matches /products?sort=price and /products?page=2 alike. Changing only the query string re-renders components that read it, but it does not change which routes match.
Reading with useSearchParams
useSearchParams returns a pair, like useState. The first item is a standard URLSearchParams object. The second is a function that updates the URL.
import { useSearchParams } from "react-router-dom";
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
const sort = searchParams.get("sort") ?? "name";
return (
<button onClick={() => setSearchParams({ sort: sort === "name" ? "price" : "name" })}>
Sorted by {sort}
</button>
);
}URLSearchParams is a browser built-in, not a React Router type. These are the methods you will use most:
| Method | Returns | Notes |
|---|---|---|
| `get("sort")` | A string, or `null` if absent | An empty value (`?sort=`) returns `""` |
| `getAll("tag")` | An array of strings | For repeated keys such as `?tag=a&tag=b` |
| `has("sort")` | A boolean | True even when the value is empty |
| `set("sort", "price")` | Nothing | Replaces every existing value for that key |
| `append("tag", "c")` | Nothing | Adds another value for the key |
| `delete("sort")` | Nothing | Removes the key |
Values are always strings
Every value from the query string is a string or null. That causes the most common bugs with search params:
const page = searchParams.get("page");
// "2", not 2
const next = page + 1;
// "21", not 3Convert the value and give it a default. Also handle input that was typed by hand into the address bar:
function parsePage(value) {
const n = Number.parseInt(value ?? "", 10);
return Number.isInteger(n) && n > 0 ? n : 1;
}
const page = parsePage(searchParams.get("page"));Treat the query string as untrusted input. A visitor can change it to anything, so check it against the values you accept:
const SORTS = ["name", "price"];
const requested = searchParams.get("sort");
const sort = SORTS.includes(requested) ? requested : "name";Updating the query string
Calling setSearchParams navigates to the same path with a new query string. It adds an entry to the browser history, so the back button returns to the previous view. React Router does not reload the page.
The function accepts several kinds of input:
setSearchParams({ sort: "price", page: "1" });
setSearchParams("sort=price&page=1");
setSearchParams([["tag", "a"], ["tag", "b"]]);
setSearchParams(new URLSearchParams({ sort: "price" }));Updates replace the whole query string
Passing an object does not merge it with the current parameters. It replaces them. If the URL is ?sort=price&page=3 and you call setSearchParams({ sort: "name" }), the result is ?sort=name, and page is gone.
To change one key and keep the rest, pass a function. It receives the current parameters and returns the next ones:
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.set("sort", "name");
next.set("page", "1");
return next;
});Copy prev before changing it, as the example does. Treat the object you receive as read-only.
The function form reads the parameters from the most recent render. It does not queue updates the way useState does. If you call setSearchParams twice in one event handler, the second call starts from the same snapshot as the first, and the first change can be lost. Combine the changes into one call.
Push or replace
Some updates should not fill the history with entries. If a search box updates the URL on every keystroke, pressing back would step through each letter. Pass replace: true to overwrite the current history entry instead:
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
if (text) next.set("q", text);
else next.delete("q");
return next;
},
{ replace: true }
);Deleting the key when the text is empty keeps the URL clean. Without that, you get ?q= in the address bar.
A complete filter example
This component combines the pieces above. It reads and validates parameters, updates one key at a time, and resets the page number when the filter changes.
import { useSearchParams } from "react-router-dom";
const SORTS = ["name", "price"];
function parsePage(value) {
const n = Number.parseInt(value ?? "", 10);
return Number.isInteger(n) && n > 0 ? n : 1;
}
export default function ProductFilters() {
const [searchParams, setSearchParams] = useSearchParams();
const requested = searchParams.get("sort");
const sort = SORTS.includes(requested) ? requested : "name";
const page = parsePage(searchParams.get("page"));
const q = searchParams.get("q") ?? "";
function update(changes, options) {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
for (const [key, value] of Object.entries(changes)) {
if (value === null || value === "") next.delete(key);
else next.set(key, String(value));
}
return next;
}, options);
}
return (
<div>
<input
value={q}
onChange={(e) => update({ q: e.target.value, page: 1 }, { replace: true })}
placeholder="Search"
/>
<select value={sort} onChange={(e) => update({ sort: e.target.value, page: 1 })}>
{SORTS.map((s) => (
<option key={s} value={s}>{s}</option>
))}
</select>
<button disabled={page === 1} onClick={() => update({ page: page - 1 })}>Previous</button>
<span> Page {page} </span>
<button onClick={() => update({ page: page + 1 })}>Next</button>
</div>
);
}The input is controlled by the URL. There is no useState for q, because the URL is the single source of truth. Resetting page to 1 when the sort or search changes avoids showing page 5 of a result set that now has two pages.
Links that carry a query string
You can set the query string without a hook by putting it in the to prop of a link:
import { Link } from "react-router-dom";
<Link to="/products?sort=price&page=1">Cheapest first</Link>
<Link to={{ pathname: "/products", search: "?sort=price" }}>Cheapest first</Link>When you build the string from user text, encode it so special characters do not break the URL:
const search = new URLSearchParams({ q: userText }).toString();
<Link to={`/products?${search}`}>Search</Link>Reading search params in a loader
A loader has no hooks. It receives the Request object, and you build a URL from it:
export async function productsLoader({ request }) {
const url = new URL(request.url);
const sort = url.searchParams.get("sort") ?? "name";
const res = await fetch(`/api/products?sort=${encodeURIComponent(sort)}`);
return res.json();
}By default, the router runs the loader again whenever the query string changes, even though the route itself did not change. That is what you want for filtering. Loaders get their own chapter, so treat this as a preview.
Common mistakes
- Expecting a merge. Passing an object to
setSearchParamsdrops every key you leave out. Use the function form to keep the others. - Forgetting that values are strings. Compare with
"2"or convert first.page + 1concatenates. - Mutating
searchParamsdirectly. CallingsearchParams.set(...)changes the object but not the URL. You must callsetSearchParams. - Duplicating state. Copying a parameter into
useStatecreates two sources of truth that drift apart after back or forward navigation. Read from the URL. - Putting private data in the URL. Query strings appear in history, logs, and shared links. Do not store tokens or personal data there.
Exercise
The URL is /products?sort=price&page=3. A handler calls setSearchParams({ sort: "name" }). What is the URL afterward, and how do you change the handler so page=3 is kept?
Show answer
The URL becomes /products?sort=name, because passing an object replaces the whole query string and page is dropped. To keep it, use the function form: setSearchParams((prev) => { const next = new URLSearchParams(prev); next.set("sort", "name"); return next; }). This copies the current parameters, changes only sort, and leaves page=3 in place.
Exercise
A search box calls setSearchParams on every keystroke, and the back button now steps through each typed letter. Which option fixes this, and how do you avoid leaving "?q=" in the URL when the box is empty?
Show answer
Pass { replace: true } as the second argument so each update overwrites the current history entry instead of adding one. When the text is empty, call next.delete("q") rather than next.set("q", ""), so the key is removed from the URL.