Managing State in URL Search Params
Sync filters, sort, and pagination to the URL with useSearchParams.
Managing State in URL Search Params is a free React Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Store State in the URL?
Filters, search queries, sort orders, and pagination belong in the URL so users can bookmark, share, and navigate back to the same view without losing state.
useSearchParams Hook
useSearchParams() returns the current URLSearchParams instance and a setter function, similar to useState but backed by the URL query string.
import { useSearchParams } from 'react-router-dom';
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
const query = searchParams.get('q') || '';
const page = Number(searchParams.get('page') || 1);
// ...
}Reading a Single Param
Use searchParams.get('key') to read a value. It returns null if the param is absent, so provide a fallback.
const sort = searchParams.get('sort') ?? 'name';
const order = searchParams.get('order') ?? 'asc';Writing Params Without Navigation
Call setSearchParams() with a new object or updater function to change params. React Router updates the URL and re-renders without a full navigation.
function SortButton({ field }) {
const [searchParams, setSearchParams] = useSearchParams();
const handleClick = () => {
setSearchParams(prev => {
prev.set('sort', field);
prev.set('page', '1');
return prev;
});
};
return <button onClick={handleClick}>Sort by {field}</button>;
}Preserving Other Params on Update
Use the updater function form of setSearchParams so you only mutate the params you intend to change, keeping all others intact.
setSearchParams(prev => {
prev.set('q', newQuery);
// 'sort' and 'page' are unchanged
return prev;
});Syncing an Input with Search Params
Control an input's value from the URL param and update the URL on change to keep them in sync.
function SearchBar() {
const [params, setParams] = useSearchParams();
const q = params.get('q') || '';
return (
<input
value={q}
onChange={e => setParams(prev => {
prev.set('q', e.target.value);
prev.set('page', '1');
return prev;
})}
/>
);
}Boolean Flags in Search Params
Use the presence or absence of a param (or a '1'/'0' string) to represent boolean UI state like an open panel or active filters.
const showFilters = searchParams.has('filters');
const toggleFilters = () => {
setSearchParams(prev => {
if (prev.has('filters')) prev.delete('filters');
else prev.set('filters', '1');
return prev;
});
};Array Values in Search Params
URLSearchParams supports multiple values for the same key. Use getAll('key') to read them as an array.
// URL: /products?tag=react&tag=typescript
const tags = searchParams.getAll('tag'); // ['react', 'typescript']
// Setting multiple values:
const newParams = new URLSearchParams();
selectedTags.forEach(t => newParams.append('tag', t));
setSearchParams(newParams);Replacing vs Pushing History
Pass { replace: true } as the second argument to setSearchParams so filter changes don't flood the browser history stack.
setSearchParams(prev => { prev.set('q', val); return prev; }, { replace: true });Deriving State from Params
Compute derived values (like parsed integers or validated enums) from raw string params at the top of your component to use safely throughout.
const rawPage = searchParams.get('page');
const page = Math.max(1, parseInt(rawPage || '1', 10));
const rawSort = searchParams.get('sort');
const sort = ['name', 'price', 'date'].includes(rawSort) ? rawSort : 'name';Linking with Search Params
Use the search property on a Link or to object to navigate to a URL with specific query params set.
<Link to={{ pathname: '/products', search: '?sort=price&order=asc' }}>
Sort by Price
</Link>Quick Check
Which method of URLSearchParams reads all values for a repeated key like ?tag=react&tag=ts?
Recap
useSearchParams() syncs component state with the URL query string. Use the updater form to preserve other params, { replace: true } to avoid history bloat, and getAll() for array-valued params.
Frequently asked questions
Is the “Managing State in URL Search Params” lesson free?
Yes — the full text of “Managing State in URL Search Params” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Managing State in URL Search Params”?
Sync filters, sort, and pagination to the URL with useSearchParams. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Managing State in URL Search Params” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Nested Routes & Outlet Layouts
- Loaders & Actions (Data Router API)
- Protected Routes & Auth Guards
- Managing State in URL Search Params