Reading Query Parameters with useSearchParams
What you'll learn: How to read and update URL search parameters (query strings) reactively in your React Router components.
What Are Search Params?
Search parameters are the key-value pairs that appear after the ? in a URL, like ?page=2&filter=active. They're perfect for storing UI state that you want to be shareable via URL (filtering, sorting, pagination, etc.).
The useSearchParams Hook
React Router provides useSearchParams to work with these query parameters reactively. It returns an array with two elements:
- A
URLSearchParamsobject (read-only snapshot of current params) - A setter function to update the params
import { useSearchParams } from 'react-router-dom';
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
// Read a parameter
const page = searchParams.get('page') || '1';
const filter = searchParams.get('filter') || 'all';
// Update parameters
const goToPage = (newPage) => {
setSearchParams({ page: newPage, filter });
};
return (
<div>
<p>Current page: {page}, Filter: {filter}</p>
<button onClick={() => goToPage('2')}>Go to Page 2</button>
</div>
);
}
How the Setter Works
When you call setSearchParams({ page: '3' }), React Router updates the URL (e.g., to ?page=3) and triggers a re-render with the new params. Think of it like useState for your URL query string—changing it updates the browser location and your component reactively responds.
You can pass an object to completely replace params, or use the URLSearchParams API methods for more control.
Key Takeaway: useSearchParams gives you reactive access to URL query parameters—read them with .get() and update them with the setter, making shareable, bookmarkable UI state trivial.