InterviewHubPRO
Section Overview
Q353

Question 353 of 445

Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

79%
React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

How do query parameters work?

Query (search) parameters are the ?key=value&key2=value2 portion of a URL. Unlike route params (see What are dynamic routes and what are route parameters?), they aren't part of the route's path definition — they're read and updated with the useSearchParams hook, which mirrors the browser's URLSearchParams API.

jsx
import { useSearchParams } from "react-router-dom";

function ProductList() {
// URL: /products?category=shoes&sort=price&page=2
const [searchParams, setSearchParams] = useSearchParams();

const category = searchParams.get("category"); // "shoes"
const sort = searchParams.get("sort");           // "price"
const page = Number(searchParams.get("page") ?? "1"); // params are always strings

function handleSortChange(nextSort) {
  // Updates the URL (?sort=...) and triggers a re-render with the new value
  setSearchParams((prev) => {
    prev.set("sort", nextSort);
    return prev;
  });
}

return (
  <div>
    <select value={sort ?? ""} onChange={(e) => handleSortChange(e.target.value)}>
      <option value="price">Price</option>
      <option value="rating">Rating</option>
    </select>
    {/* render products filtered by category, sorted by sort, paginated by page */}
  </div>
);
}

Key points:

  • useSearchParams() returns [searchParams, setSearchParams], similar to useState — searchParams is a read-only URLSearchParams instance (.get(), .getAll(), .has()), and setSearchParams() updates the URL (and re-renders).
  • Updating search params pushes a new history entry by default; pass { replace: true } as a second argument to setSearchParams to avoid cluttering back/forward history (useful for things like live search-as-you-type).
  • Query params are ideal for optional, non-hierarchical, shareable UI state — filters, sorting, pagination, search text — because the resulting URL can be bookmarked/shared and still reproduces the same view.
  • Unlike route params, missing query params don't cause a 404/no-match; searchParams.get("missing") simply returns null, so always provide sensible defaults.