How do you get query parameters from a URL?
What query parameters are
An example URL:
javascript
https://example.com/products?page=2&sort=price_asc&category=shirtsQuery parameters are the part after ?:
javascript
page=2&sort=price_asc&category=shirtsWay 1. Through the useSearchParams() hook (React Router v6+)
This is the most convenient and most "React-ish" way if you use react-router-dom.
javascript
import { useSearchParams } from "react-router-dom";
function ProductList() {
const [searchParams] = useSearchParams();
const page = searchParams.get("page");
const sort = searchParams.get("sort");
const category = searchParams.get("category");
return (
<div>
<p>Page: {page}</p>
<p>Sort: {sort}</p>
<p>Category: {category}</p>
</div>
);
}If the user opens:
/products?page=2&sort=price_asc&category=shirts
you get:
javascript
page = "2"
sort = "price_asc"
category = "shirts"Way 2. Through useLocation() + URLSearchParams
If you need more control over the URL (for example, combining it with the hash or pathname):
javascript
import { useLocation } from "react-router-dom";
function ProductList() {
const location = useLocation();
const params = new URLSearchParams(location.search);
const page = params.get("page");
const sort = params.get("sort");
return (
<p>Page: {page}, Sort: {sort}</p>
);
}location.search returns a string like "?page=2&sort=asc",
and URLSearchParams turns it into a convenient API for reading.
Way 3. Without React Router (plain JavaScript)
If you do not use react-router-dom, you can read the parameters directly from window.location.
javascript
const params = new URLSearchParams(window.location.search);
const page = params.get("page");
const sort = params.get("sort");
console.log(page, sort);Works in any modern browser.
Additional URLSearchParams capabilities
javascript
const params = new URLSearchParams("?page=2&sort=asc&filter=red");
params.get("page"); // "2"
params.has("filter"); // true
params.getAll("tag"); // all values with the same key
params.toString(); // "page=2&sort=asc&filter=red"
for (const [key, value] of params.entries()) {
console.log(key, value);
}What to choose
| Approach | When to use it |
|---|---|
useSearchParams() | For most cases in React Router v6+ (a convenient API and automatic synchronization) |
useLocation() + URLSearchParams | When you need more control (for example, combining it with pathname or state) |
window.location | Outside React Router, for example in plain JS code or an external script |
Summary:
To get query parameters in React:
through React Router:
javascriptconst [params] = useSearchParams(); const page = params.get("page");through native JS:
javascriptconst params = new URLSearchParams(window.location.search); const page = params.get("page");
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.