What is Dynamic Routing?
Dynamic routing allows you to define a single route path that can match multiple URLs based on a pattern. Instead of creating a separate route for every user or product, you use placeholders (params) to capture values from the URL and use them to fetch specific data.
URL Parameters (useParams)
To define a dynamic segment, you prefix the path part with a colon :. React Router will then capture whatever value is in that position and make it available via the useParams hook.
Query Strings (useSearchParams)
Query strings are the key-value pairs at the end of a URL (e.g., /search?query=react&sort=asc). Unlike path params, these are optional and handled via the useSearchParams hook, which works similarly to useState.
Use Cases for Dynamic Routing
- User Profiles:
/profile/:usernamematches/profile/kishoreand/profile/john. - E-commerce:
/category/:cid/product/:pidfor deeply nested resource matching. - Pagination:
/blog/page/:pageNumberfor clean, shareable list views. - Filtering: Using query strings for sort order, price ranges, and search filters.
Comparison: Params vs. Search Query
| Feature | URL Parameters (:id) | Search Params (?q=) |
|---|---|---|
| Requirement | Required for the route to match | Optional/Flexible |
| Structure | Part of the path (/user/123) | Appended at end (?id=123) |
| Best For | Identifying a specific resource | Filtering, sorting, searching |
| Hook | useParams() | useSearchParams() |