useParams returns an object of key/value pairs of the dynamic parameters from the current URL that were matched by the <Route path>.
<Route path="/users/:userId" element={<UserProfile />} />import { useParams } from "react-router";
function UserProfile() {
const { userId } = useParams();
return <h1>User ID: {userId}</h1>;
}
// URL: /users/42 → userId = "42"<Route path="/c/:categoryId/p/:productId" element={<Product />} />import { useParams } from "react-router";
function Product() {
const { categoryId, productId } = useParams();
return (
<div>
<h1>Category: {categoryId}</h1>
<h2>Product: {productId}</h2>
</div>
);
}
// URL: /c/electronics/p/laptop-123
// categoryId = "electronics", productId = "laptop-123"import { useParams } from "react-router";
import { useState, useEffect } from "react";
function ProductDetail() {
const { productId } = useParams();
const [product, setProduct] = useState(null);
useEffect(() => {
fetch(`/api/products/${productId}`)
.then(res => res.json())
.then(data => setProduct(data));
}, [productId]);
if (!product) return <p>Loading...</p>;
return (
<div>
<h1>{product.name}</h1>
<p>Price: ${product.price}</p>
</div>
);
}<Route path="files/*" element={<FileViewer />} />import { useParams } from "react-router";
function FileViewer() {
const { "*": filePath } = useParams();
return <p>Viewing file: {filePath}</p>;
}
// URL: /files/docs/readme.md → filePath = "docs/readme.md"<Routes>
<Route path="/blog/:slug" element={<BlogPost />}>
<Route path="comments/:commentId" element={<Comment />} />
</Route>
</Routes>// In Comment component — has access to BOTH params
function Comment() {
const { slug, commentId } = useParams();
return (
<div>
<p>Blog: {slug}</p>
<p>Comment: {commentId}</p>
</div>
);
}const { userId } = useParams();
console.log(typeof userId); // "string"
// Convert to number if needed
const numericId = Number(userId);<Route path=":lang?/categories" element={<Categories />} />function Categories() {
const { lang } = useParams();
// URL: /categories → lang = undefined
// URL: /en/categories → lang = "en"
}useParamsreturns an object with param names as keys- All param values are strings — convert manually if needed
- Child routes have access to all parent route params
- Use
*(splat) to capture remaining URL segments - Optional params return
undefinedwhen not present - Param names must be unique within a route path