Part 26: Dynamic Routes, URL Parameters & Query Strings
Modern applications require dynamic URLs: /products/123, /users/alex/settings, or /search?q=react&sort=desc.
1. Dynamic Route Parameters (useParams)
Declare a route segment starting with a colon : to mark it as a dynamic parameter:
<Route path="/products/:productId" element={<ProductDetail />} />
Reading the Parameter:
import { useParams } from 'react-router-dom';
export default function ProductDetail() {
const { productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Currently viewing Product ID: <strong>{productId}</strong></p>
</div>
);
}
2. Managing Search Query Strings (useSearchParams)
React Router provides useSearchParams, which behaves similarly to useState:
import { useSearchParams } from 'react-router-dom';
export default function ArticleSearch() {
const [searchParams, setSearchParams] = useSearchParams();
const query = searchParams.get('q') || '';
const sort = searchParams.get('sort') || 'latest';
const handleSearchChange = (newQuery) => {
setSearchParams({ q: newQuery, sort });
};
return (
<div>
<input
type="text"
value={query}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search keywords..."
className="border p-2 rounded"
/>
<p>Active Query: {query}</p>
<p>Active Sort: {sort}</p>
</div>
);
}
Key Takeaways
- Use
:paramNamein Route paths and read them withuseParams(). - Use
useSearchParams()to read and update query string parameters synchronously with the URL.
In Part 27, we will explore Nested Routes, Layouts, and the <Outlet /> Component!

