When a route's path pattern includes a dynamic segment, written with a leading colon like '/products/:productId', useParams() lets the component rendered for that route read the actual value that was matched in the current URL — visiting '/products/42' with that route pattern makes useParams() return { productId: '42' }. Every matched parameter comes through as a string, even if it looks numeric, so an id used for something like an array lookup or an API call expecting a number typically needs an explicit conversion first.
1Understanding useParams
When a route's path pattern includes a dynamic segment, written with a leading colon like '/products/:productId', useParams() lets the component rendered for that route read the actual value that was matched in the current URL — visiting '/products/42' with that route pattern makes useParams() return { productId: '42' }. Every matched parameter comes through as a string, even if it looks numeric, so an id used for something like an array lookup or an API call expecting a number typically needs an explicit conversion first.
Every value returned by useParams() is always a string, even a numeric-looking one like an id — convert it explicitly with Number() or parseInt() before using it anywhere that expects an actual number, like an array index.
import { useParams } from 'react-router-dom';
function ProductPage() {
const { productId } = useParams();
return <p>Showing product: {productId}</p>;
}
// Route path="/products/:productId", visiting /products/422Practical Example
Here is a real-world application of useParams showing how it is used in production React code.
import { useParams } from 'react-router-dom';
function UserPost() {
const { userId, postId } = useParams();
return <p>User {userId}, Post {postId}</p>;
}
// Route path="/users/:userId/posts/:postId", visiting /users/7/posts/1233Best Practices
Follow these guidelines when working with useParams:
1. Convert route parameters from useParams() to the expected type, like Number(id), before using them for numeric comparisons, array indexing, or type-sensitive API calls
2. Name a route's dynamic segment clearly, like ':productId' rather than a generic ':id', especially when a route has more than one dynamic parameter
3. Handle the case where a matched parameter doesn't correspond to any real underlying data, like a productId that doesn't exist, rather than assuming useParams() always returns a valid, existing identifier
Tip: Every value returned by useParams() is always a string, even a numeric-looking one like an id — convert it explicitly with Number() or parseInt() before using it anywhere that expects an actual number, like an array index.
import { useParams } from 'react-router-dom';
function ProductPage() {
const { productId } = useParams();
return <p>Showing product: {productId}</p>;
}
// Route path="/products/:productId", visiting /products/42