Working with Query Param
Query parameters are the key-value pairs after the ? in a URL, like /products?category=books&sort=price. In React Router you read and update them with the useSearchParams hook. You use them for state that should survive a page refresh and be shareable as a link: search terms, filters, sort order and the current page number.
Route params versus query params
| Route parameter | Query parameter | |
|---|---|---|
| Example URL | /products/42 | /products?sort=price |
| Declared in the route? | Yes, as :productId | No, any route can receive them |
| Typical use | Identifies which resource | Options that change how it is shown |
| Read with | useParams() | useSearchParams() |
| Optional? | Required for the route to match | Always optional |
Reading and updating with useSearchParams
useSearchParams returns a pair, similar to useState: a URLSearchParams object for reading, and a setter that updates the URL. Changing the URL causes a re-render with the new values.
import { useSearchParams } from 'react-router-dom';
function ProductList({ products }) {
const [searchParams, setSearchParams] = useSearchParams();
const sort = searchParams.get('sort') ?? 'name';
const page = Number(searchParams.get('page') ?? '1');
const sorted = [...products].sort((a, b) =>
sort === 'price' ? a.price - b.price : a.name.localeCompare(b.name)
);
function changeSort(value) {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.set('sort', value);
next.set('page', '1');
return next;
});
}
return (
<>
<button onClick={() => changeSort('name')}>By name</button>
<button onClick={() => changeSort('price')}>By price</button>
<p>Page {page}</p>
<ul>{sorted.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
</>
);
}
get() returns null when a key is missing, which is why the code uses ?? to supply defaults. Other handy methods on the same object are has(key) to check presence, getAll(key) for repeated keys such as ?tag=js&tag=css, and delete(key) to remove one.
Why keep this state in the URL
You could store the sort order in useState instead. The difference shows up the moment someone refreshes the page or copies the link to a friend: component state resets to its default, while the URL keeps the exact view. Back and Forward buttons also work naturally, because each view has its own address. Keep short-lived UI details, like whether a dropdown is open, in component state, and put anything a user might want to bookmark or share in the query string.
Values are always strings
Everything in a query string is text. searchParams.get('page') returns "2", not 2. Doing arithmetic like page + 1 on the raw value gives "21". Convert numbers with Number() and booleans with a comparison like get('inStock') === 'true', and guard against nonsense values that users might type into the address bar.
The pitfall of replacing every parameter
Calling setSearchParams({ sort: 'price' }) replaces the whole query string. Any other parameter, such as category=books, is silently dropped, and the user loses their filter. To change one value and keep the rest, pass a function that copies the previous params, as the example does, and set only the key you mean to change.
Also think about history. Each update adds a browser history entry by default, so pressing Back steps through every sort click. For rapid changes like typing in a search box, pass { replace: true } as the second argument to update the current entry instead.
Building links with query strings
You can also put query parameters straight into links: <Link to="/products?sort=price">. When values come from user input, build the string with new URLSearchParams({ q: term }).toString() so spaces and special characters are encoded correctly.
In short: use route params to pick a resource, query params for options, convert strings before using them, and update one key at a time without dropping the others.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.