Keeping React Router Filter Conditions in the URL with useSearchParams
When you put the filter conditions for a list in the URL query (the part like ?color=white&sort=age), the same filtered list is shown after you reload the page or send the URL to someone else. The browser's Back button also returns to the previous conditions. In React Router, you can read and write the query with useSearchParams, so you don't need to copy the conditions into useState.
In my test environment, I built a screen that filters a list of cats by name, fur color, and sort order, and checked it by operating it in the browser. Through this, I found three things to watch out for: how to record history for the search box, the caret jumping to the end of an input field, and what happens when setSearchParams is called several times in a row.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 141. I used react-router 8.5.0, react and react-dom 19.3.1, @types/react 19.3.0, and typescript 7.0.2. I ran the code converted with esbuild (a development build) in Chromium and operated it with Playwright. The router was the declarative BrowserRouter, and I only tested a screen that runs entirely in the browser. I did not test data mode (createBrowserRouter), loaders combined with it, or server rendering.
- 1. Read the conditions from the URL query on every render
- 2. Change the conditions by rewriting the URL with setSearchParams
- 3. Don't add a history entry for every keystroke in the search box
- 4. If the caret jumps to the end of the input, set useTransitions to false
- 5. Don't call setSearchParams twice for one action
Read the conditions from the URL query on every render
As described in the useSearchParams reference, useSearchParams returns a URLSearchParams object that represents the query of the current URL, along with a function that rewrites it. The conditions are read from this searchParams on every render. Because they are never copied into useState, the URL and the screen state cannot drift apart. The React Router state management explanation also gives, as an example to avoid, keeping state that can live in the URL in both React state and the URL, and synchronizing them.
Put the reading logic in a function. Users can edit the URL by hand, so the function should handle unexpected values gracefully.
import { COLORS, type Color } from './cats';
export type Sort = 'name' | 'age';
const isColor = (v: string): v is Color => (COLORS as readonly string[]).includes(v);
// Read the filter conditions from the URL query. Ignore unknown values and use the defaults
export function readFilters(searchParams: URLSearchParams) {
const q = searchParams.get('q') ?? '';
const colors = searchParams.getAll('color').filter(isColor);
const sort: Sort = searchParams.get('sort') === 'age' ? 'age' : 'name';
return { q, colors, sort };
}
For a condition where you can select several values, such as fur color, repeat the same name, as in ?color=white&color=orange, and read it as an array with getAll. As the MDN description of getAll says, it returns an empty array when there are no values.
In the component, you only filter the list with the conditions you read.
import { useSearchParams } from 'react-router';
import { CATS, COLORS, COLOR_LABELS, type Color } from './cats';
import { readFilters, type Sort } from './filters';
export function CatList() {
const [searchParams, setSearchParams] = useSearchParams();
const { q, colors, sort } = readFilters(searchParams);
const visible = CATS.filter(
(cat) => cat.name.includes(q) && (colors.length === 0 || colors.includes(cat.color)),
).sort((a, b) => (sort === 'age' ? a.age - b.age : a.name.localeCompare(b.name, 'ja')));
// toggleColor, changeSort, and the rendering part are covered in the next section; changeQuery is covered in the search box history section
}
In the test, when I opened /cats?color=white&color=orange&sort=age directly, the white and orange tabby checkboxes were checked, the sort was set to age, and four cats were shown in order of age, youngest first.

I also opened a URL with unknown values mixed in, such as /cats?sort=zzz&color=purple&color=black. The sort fell back to the default, name, and purple was ignored, so only the two black cats were shown. The URL was not rewritten and stayed as I had opened it.
Change the conditions by rewriting the URL with setSearchParams
To change a condition, rewrite the URL with setSearchParams. According to the useSearchParams reference, calling setSearchParams causes navigation to the new URL. Like a useState updater, you can also pass a function that receives the current query and returns the new one.
function toggleColor(color: Color, checked: boolean) {
setSearchParams((prev) => {
const next = COLORS.filter((c) => (c === color ? checked : colors.includes(c)));
prev.delete('color');
for (const c of next) prev.append('color', c);
return prev;
});
}
function changeSort(value: Sort) {
setSearchParams((prev) => {
if (value === 'name') prev.delete('sort');
else prev.set('sort', value);
return prev;
});
}
When the default value (name for sort) is selected, the code removes sort from the query. This keeps the URL short, as /cats, for a screen with no conditions. For fur color, the values are always rebuilt in the order of COLORS before being added, so the order you check boxes in never changes the URL.
In the test, checking black and then white still gave ?color=white&color=black, the same as checking white and then black. Choosing age for sort and then switching back to name removed sort from the URL.
The prev passed to the function is not the searchParams object that useSearchParams returns. In the source of the installed react-router 8.5.0, it passes a copy made with new URLSearchParams(searchParams). So rewriting prev does not change the searchParams used during the current render.
For the screen itself, every input value comes from the conditions read from the URL. The clear button passes an empty object to remove all query parameters.
return (
<main>
<label>
名前で探す
<input type="search" value={q} onChange={(e) => changeQuery(e.target.value)} />
</label>
<fieldset>
<legend>毛の色</legend>
{COLORS.map((c) => (
<label key={c}>
<input
type="checkbox"
checked={colors.includes(c)}
onChange={(e) => toggleColor(c, e.target.checked)}
/>
{COLOR_LABELS[c]}
</label>
))}
</fieldset>
<label>
並び順
<select value={sort} onChange={(e) => changeSort(e.target.value as Sort)}>
<option value="name">名前</option>
<option value="age">年齢</option>
</select>
</label>
<button type="button" onClick={() => setSearchParams({})}>
条件をクリア
</button>
{/* List rendering omitted */}
</main>
);
In the test, I opened /cats, checked white and then black, and selected age for sort. In the test environment, history.length was 2 when /cats was opened. Below, I compare the increase from that value. The URL changed with each action to ?color=white, ?color=white&color=black, and ?color=white&color=black&sort=age, and history.length grew by one each time, from 2 to 5. Pressing Back returned the sort to name, and pressing Back again returned to the state where black was unchecked. Forward restored the white and black state, and reloading there kept the conditions. Pressing the clear button changed the URL to /cats and showed all seven cats.
Don't add a history entry for every keystroke in the search box
The type definition in the installed react-router 8.5.0 shows that the second argument of setSearchParams is NavigateOptions. In the source, the value is passed straight to navigate. So you can pass the same navigation options that useNavigate accepts. As the useNavigate reference describes, passing replace: true replaces the current entry instead of adding a new one to the history.
If changeQuery in the search box does not specify replace, each typed character adds one history entry. So I wrote three versions of changeQuery. I checked each one by checking white, typing しろ one character at a time, pressing Back once, and comparing the results.
How changeQuery is written |
history.length (before → after typing) |
After one Back |
|---|---|---|
No replace |
3 → 5 | The search box shows し |
Always replace: true |
3 → 3 | Back to /cats, and the white checkbox is also cleared |
| Add only the first character, replace the rest | 3 → 4 | The search box is empty, and the white checkbox stays checked |

When I always used replace: true, even the entry from before typing (the state with white checked) was replaced. As a result, pressing Back also cleared the white checkbox. I settled on a version that adds a history entry only for the first character typed, when the URL does not yet have q, and replaces the entry for every character after that.
function changeQuery(value: string) {
setSearchParams(
(prev) => {
if (value === '') prev.delete('q');
else prev.set('q', value);
return prev;
},
{ replace: searchParams.has('q') },
);
}
In the test code, the three versions can be switched at build time. The code above is the version rewritten to "add only the first character."
If the caret jumps to the end of the input, set useTransitions to false
All the tests so far used BrowserRouter with useTransitions={false}. I did this because, without it (the default), the input field behaved strangely.
With the default setting, I opened /cats?q=こむぎ, placed the caret at the start of the search box, and typed お. The box became おこむぎ, but the caret position (selectionStart) was 4, not 1, so it had moved to the end. When I then typed ば, the result was おこむぎば, not おばこむぎ. For the checkbox, the URL had already become ?color=white right after the click, but checked was still false. It was still false after setTimeout(0), and it only became true when I read it 100 ms later. So the URL changed first, and the checkbox display switched afterward.
With useTransitions={false}, the caret stayed at position 1, and the subsequent typing produced おばこむぎ. The checkbox was already true right after the click.
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Route, Routes } from 'react-router';
import { CatList } from './CatList';
createRoot(document.getElementById('root')!).render(
<BrowserRouter useTransitions={false}>
<Routes>
<Route path="/cats" element={<CatList />} />
</Routes>
</BrowserRouter>,
);
In the test code, the value passed to useTransitions is switched at build time. The code also includes a part that shows the current URL on screen and the route for the page used in the next section.
According to the BrowserRouter reference, if useTransitions is not specified, all router state updates are wrapped in React.startTransition. Setting it to false stops using startTransition. In the source of the installed 8.5.0, the state was updated as-is only when useTransitions === false.
The React useTransition reference says that a state update that determines an input's value cannot be made a Transition, because updates that respond to input must be synchronous. With the default useTransitions, if you use the URL query value as the input's value, you get exactly this situation. The same section also covers keeping a separate synchronously updated state for the input and using useDeferredValue, but I did not test those approaches on this screen.
useTransitions={false} changes the behavior of the entire router. The React Router explanation of Transitions also covers the benefits of using Transitions, such as avoiding the fallback shown in place of Suspense during navigation. I only tested the behavior of the input field and checkboxes on this screen.
Don't call setSearchParams twice for one action
A function passed to setSearchParams looks similar to a useState updater, but the results differ when it is called in succession. I tested this with a button that, on one click, makes two calls in a row: one that adds white and one that adds black.
function selectTwiceSeparately() {
setSearchParams((prev) => {
prev.append('color', 'white');
return prev;
});
setSearchParams((prev) => {
prev.append('color', 'black');
return prev;
});
}
After pressing it, the URL was ?color=black, and white was not kept. history.length went from 2 to 4, so two navigations happened. When I made both changes inside one function and called setSearchParams once, the URL became ?color=white&color=black.
The useSearchParams reference also notes that the function form has no queue like setState. So calling it several times in the same tick does not base later calls on the results of earlier ones. In the 8.5.0 source, both calls received a copy of the searchParams from the render as prev.
Read the conditions from searchParams every time, and call setSearchParams only once per action when changing them. Replace the search box's history entries while typing. If you use the URL query value as the input's value, set useTransitions={false} and check that the caret behaves correctly.





