Sub topic 8
Reading and updating the query string
The query string is the part of a URL after ?, such as /products?sort=price&page=2. It suits state that a user should be able to bookmark or share, such as sort order, filters, and page number. This chapter assumes you can write React function components and hooks, and that you have a working router from the earlier chapters.
Reading values with useSearchParams
useSearchParams returns a pair, similar to useState. The first item is a URLSearchParams object. The second is a function that updates it.
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>
);
}get returns null when the key is missing, so the ?? operator supplies a default. Calling setSearchParams changes the URL and re-renders the component. The URL is the source of truth, so you don't need a separate useState for these values.
Rules to remember
- Every value is a string or
null. Convert numbers yourself, for exampleNumber(searchParams.get("page") ?? 1). - Query strings never take part in route matching.
/products?sort=priceand/productsmatch the same route. - Use
getAll("tag")when a key repeats, as in?tag=a&tag=b. - Use
has("sort")to check whether a key is present.
Updating without losing other params
Passing an object to setSearchParams replaces the whole query string. If the URL was ?sort=price&page=3 and you call setSearchParams({ sort: "name" }), the page value is gone. To keep the other keys, pass a function that receives the current params:
import { useSearchParams } from "react-router-dom";
function Pagination() {
const [searchParams, setSearchParams] = useSearchParams();
const page = Number(searchParams.get("page") ?? 1);
function goToPage(next) {
setSearchParams(
(prev) => {
const params = new URLSearchParams(prev);
params.set("page", String(next));
return params;
},
{ replace: true }
);
}
return (
<div>
<button disabled={page <= 1} onClick={() => goToPage(page - 1)}>Previous</button>
<span> Page {page} </span>
<button onClick={() => goToPage(page + 1)}>Next</button>
</div>
);
}The code copies prev into a new URLSearchParams instead of changing it in place. The second argument, { replace: true }, overwrites the current history entry. Without it, each update adds an entry, and the Back button steps through every earlier value. Use replace for small changes such as typing in a search box. Leave it off when each state is something the user may want to return to.
Linking to a query string
You can also write the query directly in a link:
<Link to="/products?sort=price">Cheapest first</Link>Where this fits
Loaders, covered later, cannot call hooks. They read the query string from the request instead, with new URL(request.url).searchParams. The same URLSearchParams methods apply there.
Exercise
The URL is /products?sort=price&page=3. A button calls setSearchParams({ sort: "name" }). What is the URL afterward, and how would you change the call to keep page=3?
Show answer
The URL becomes /products?sort=name, because the object replaces the whole query string and page is dropped. To keep it, pass a function: setSearchParams((prev) => { const params = new URLSearchParams(prev); params.set("sort", "name"); return params; }). The URL then becomes /products?sort=name&page=3.