Routingbeginner
Dynamic Route Parameters
Learn how to define routes with dynamic URL segments and read their values inside a matched component.
Dynamic route segments let a single route definition match many different URLs that share a pattern, such as /products/:productId matching /products/42, /products/99, and so on. The colon-prefixed segment (:productId) is a placeholder that React Router captures from the actual URL and makes available to the matched component.
A dynamic route is like a mail slot labeled 'Apartment :number' instead of one labeled 'Apartment 4B' — the same slot design handles any apartment number, and whoever's checking the mail (the component) reads off exactly which number was written on this particular piece of mail (the current URL).
Key Concepts
1
Inside a component rendered by a route with dynamic segments, the useParams() hook returns an object mapping each parameter name to its actual string value extracted from the current URL — for /products/:productId matched against /products/42, useParams() returns { productId: '42' }. Since URL segments are always strings, numeric IDs need explicit conversion if used as numbers elsewhere.
useParams()/products/:productId/products/42{ productId: '42' }
2
Dynamic segments commonly drive data fetching: a component reads the ID from useParams() and uses it as a dependency for a useEffect-based fetch (or a data-fetching library's query key), so navigating to a different /products/:productId URL re-triggers fetching the newly requested product's data.
useParams()useEffect/products/:productId
3
Interviewers frequently pair this topic with data fetching, asking candidates to wire up a detail page that reads an ID from the URL and fetches the corresponding resource, checking that they remember to include the param in the fetch's dependency array so navigating between different IDs triggers a proper refetch rather than showing stale data from the previous ID.