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

codeTap to expand ⛶
1import { useParams, useSearchParams, Link } from 'react-router-dom';
2
3function ProductDetail() {
4 // 1. Accessing URL Params (:id)
5 const { id } = useParams();
6
7 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}
14
15function SearchPage() {
16 // 2. Accessing and Updating Search Params (?q=...)
17 const [searchParams, setSearchParams] = useSearchParams();
18 const query = searchParams.get('q') || '';
19
20 const handleSearch = (e) => {
21 const value = e.target.value;
22 // Update the URL without a reload
23 setSearchParams({ q: value });
24 };
25
26 return (
27 <div>
28 <input
29 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

  1. Build a 'User Profile' page that displays a different user based on the ID in the URL.
  2. Implement a 'Sort' feature using search parameters (e.g., ?sort=price_asc).
  3. Create a 'Breadcrumbs' component that parses the current URL path to show the navigation trail.
  4. Try to use useNavigate to 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 useParams hook (they are separate!).

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Dynamic Routes & Params