React › Routing

How do you read a dynamic value from the URL, such as a product id, using React Router?

Intermediate

Answer

You define a route with a colon before a name, like colon id, and React Router's useParams hook then gives you access to that specific value from the current web address inside your component.
<Route path="/products/:id" element={<ProductDetail />} />

function ProductDetail() {
  const { id } = useParams();
  return <p>Showing details for product {id}</p>;
}
Real-world example An online store shows the correct product details page for whichever product id appears in the web address, such as slash products slash 42, using useParams to read that value directly.

Common follow-ups: What happens if a user visits a product page with an id that does not actually exist?;Can a single route have more than one dynamic parameter?