Skip to main content

Lesson 4 of 10

Dynamic Routes & URL Params

Dynamic route segments (`:id`, `:slug`) let one route definition match many URLs. Combined with useParams and useSearchParams, you can build fully parameterized pages - product pages, user profiles, filtered lists - all driven by the URL.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

useParams & useSearchParams

useParams & useSearchParams
import { useParams, useSearchParams, Link } from 'react-router-dom';

// Route: <Route path="products/:productId" element={<ProductDetail />} />
function ProductDetail() {
  const { productId } = useParams<{ productId: string }>();
  // For /products/abc-123 → productId = "abc-123"

  const { data: product, isLoading } = useQuery(
    ['product', productId],
    () => fetchProduct(productId!)
  );

  if (isLoading) return <Skeleton />;
  if (!product) return <Navigate to="/404" replace />;
  return <ProductView product={product} />;
}

// useSearchParams - query string management (?sort=price&page=2)
function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();

  const sort = searchParams.get('sort') ?? 'name';   // 'price' | 'name' | 'rating'
  const page = Number(searchParams.get('page') ?? 1);
  const category = searchParams.get('category') ?? 'all';

  function handleSortChange(newSort: string) {
    setSearchParams(prev => {
      prev.set('sort', newSort);
      prev.set('page', '1'); // reset to page 1 when sort changes
      return prev;
    });
  }

  return (
    <>
      <select value={sort} onChange={e => handleSortChange(e.target.value)}>
        <option value="name">Name</option>
        <option value="price">Price</option>
        <option value="rating">Rating</option>
      </select>
      {/* URL becomes /products?sort=price&page=1 - shareable, bookmarkable */}
    </>
  );
}

// Multiple dynamic segments
// Route: <Route path="blog/:year/:month/:slug" element={<Post />} />
// URL: /blog/2026/03/react-hooks-guide
function Post() {
  const { year, month, slug } = useParams<{
    year: string; month: string; slug: string;
  }>();
  // ...
}

Common Mistakes - Dynamic Routes

  • Not handling null params - `useParams()` returns `string | undefined`; always use TypeScript and null-check before using the param in API calls
  • Encoding special characters - URLs can't contain spaces or special characters; use `encodeURIComponent()` when building Link `to` props with dynamic values
  • Reading searchParams directly - `searchParams.get('key')` returns null if the param doesn't exist, not an empty string; always provide a fallback with `?? defaultValue`
  • Mutating URL params directly - always use `setSearchParams()` to update query params; never manipulate `window.location.search` in a React Router app

Tip

Tip

Practice Dynamic Routes URL Params in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for Dynamic Routes & URL Params

Practice Task

Note

Practice Task - (1) Write a working example of Dynamic Routes URL Params from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Dynamic Routes URL Params is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Dynamic route segments (`:id`, `:slug`) let one route definition match many URLs.
  • Not handling null params - `useParams()` returns `string | undefined`; always use TypeScript and null-check before using the param in API calls
  • Encoding special characters - URLs can't contain spaces or special characters; use `encodeURIComponent()` when building Link `to` props with dynamic values
  • Reading searchParams directly - `searchParams.get('key')` returns null if the param doesn't exist, not an empty string; always provide a fallback with `?? defaultValue`

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done