Dynamic Routes & Params
0/2 in this phase0/36 across the roadmap
📖 Concept
In a real app, you don't define a separate route for every product or user. You use Dynamic Segments.
URL Parameters (Params):
Segments of the URL that start with a colon (:).
Example: /product/:id matches /product/123 and /product/abc.
You access these using the useParams() hook.
Search Parameters (Query Strings):
The part of the URL after the ?.
Example: /search?q=react&sort=newest.
You access and update these using the useSearchParams() hook.
💻 Code Example
code
1import { useParams, useSearchParams, Link } from 'react-router-dom';23function ProductDetail() {4 // 1. Accessing URL Params (:id)5 const { id } = useParams();67 return (8 <div>9 <h1>Product ID: {id}</h1>10 <Link to="/products" className="text-blue-500 underline">Back to List</Link>11 </div>12 );13}1415function SearchPage() {16 // 2. Accessing and Updating Search Params (?q=...)17 const [searchParams, setSearchParams] = useSearchParams();18 const query = searchParams.get('q') || '';1920 const handleSearch = (e) => {21 const value = e.target.value;22 // Update the URL without a reload23 setSearchParams({ q: value });24 };2526 return (27 <div>28 <input29 value={query}30 onChange={handleSearch}31 placeholder="Filter results..."32 className="border p-2"33 />34 <p>Searching for: {query}</p>35 </div>36 );37}
🏋️ Practice Exercise
- Build a 'User Profile' page that displays a different user based on the ID in the URL.
- Implement a 'Sort' feature using search parameters (e.g.,
?sort=price_asc). - Create a 'Breadcrumbs' component that parses the current URL path to show the navigation trail.
- Try to use
useNavigateto redirect a user programmatically after they submit a form.
⚠️ Common Mistakes
Forgetting the colon (
:) when defining a dynamic route.Not handling cases where a param or search param might be missing (undefined).
Thinking search params are part of the
useParamshook (they are separate!).
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Dynamic Routes & Params
Was this topic helpful?