ReactEasy
What is a query string?
A query string is the part of a URL after ?, made of key-value pairs separated by &, such as ?q=shoes&sort=price&page=2. It carries optional, shareable state: search terms, filters, sorting and pagination. In React you read and update it with the router's useSearchParams() hook, which wraps the standard URLSearchParams API.
Reading and writing
const [searchParams, setSearchParams] = useSearchParams()(React Router).searchParams.get("q"),searchParams.getAll("tag")for repeated keys,searchParams.has("page").setSearchParams({ q: "shoes", page: "1" })or a function(prev) => { prev.set("page", "2"); return prev; }.setSearchParams(next, { replace: true })for live filters, so history is not flooded.- In loaders:
new URL(request.url).searchParams.
Why use the URL for this state
- Users can bookmark, share and reload without losing filters.
- Back and Forward work naturally.
- Server rendering can read the same values.
Tips
- Values are strings; parse and validate (Zod's
z.coerce.number()). - Encode values automatically by using
URLSearchParamsinstead of string concatenation. - Remove keys with default values to keep URLs clean.
- Debounce updates from text inputs.
- Libraries like
nuqsgive type-safe, hook-based search param state.
Next.js
useSearchParams() from next/navigation in Client Components, or the searchParams prop (a Promise) in pages.
Code example
tsx
1import { useSearchParams } from "react-router";23export function ProductFilters() {4 const [searchParams, setSearchParams] = useSearchParams();5 const q = searchParams.get("q") ?? "";6 const sort = searchParams.get("sort") ?? "relevance";7 const page = Number(searchParams.get("page") ?? 1);89 function update(key: string, value: string) {10 setSearchParams(11 (prev) => {12 if (value) prev.set(key, value);13 else prev.delete(key);14 if (key !== "page") prev.delete("page"); // reset paging when filters change15 return prev;16 },17 { replace: key === "q" } // typing should not create history entries18 );19 }2021 return (22 <div>23 <input value={q} onChange={(e) => update("q", e.target.value)} placeholder="Search" />24 <select value={sort} onChange={(e) => update("sort", e.target.value)}>25 <option value="relevance">Relevance</option>26 <option value="price">Price</option>27 </select>28 <button onClick={() => update("page", String(page + 1))}>Page {page + 1}</button>29 </div>30 );31}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.