useParams Hook in React JS
The useParams() hook is provided by React Router to access dynamic parameters from the current URL. It allows developers to retrieve values such as product IDs, user IDs, student IDs, and article slugs, and use them to display the appropriate content in a React application.
React JS Training: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. What Is the useParams Hook?
useParams() is a React Router hook that returns an object containing the dynamic parameters matched by the current route. These parameters are defined in the route path using a colon (:) followed by a parameter name.
For example, consider this route:
<Route path="/users/:userId" element={<UserProfile />} />
If the user visits /users/25, the useParams() hook can retrieve the value "25" through the userId parameter.
Key Features
- Retrieves dynamic values from the current route URL.
- Works with dynamic route segments defined in Route.
- Supports routes containing multiple parameters.
- Allows reusable components to display different records.
- Child routes inherit parameters from their parent routes.
2. Why Do We Need useParams?
Many applications need to display different information based on the URL. Instead of creating a separate component for every product, user, or article, developers can use one component and retrieve the relevant identifier with useParams().
| Application |
Example URL |
Parameter |
| E-commerce |
/products/101 |
productId = "101" |
| User profiles |
/users/25 |
userId = "25" |
| Education portal |
/students/50 |
studentId = "50" |
| Blog application |
/posts/react-basics |
postSlug = "react-basics" |
| Order management |
/orders/5001 |
orderId = "5001" |
3. Installing React Router
If React Router is not already installed, open the terminal in your project directory and run:
npm install react-router
The examples in these notes use the current declarative API and import from react-router. If you are working on an existing project, use the package and syntax that match its installed React Router version.
4. Setting Up BrowserRouter
Before using useParams(), configure a router and define the route that contains the dynamic parameter.
main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router";
import App from "./App.jsx";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
BrowserRouter provides the routing context required by React Router components and hooks.
5. Basic Syntax of useParams()
Import useParams from React Router and call it inside a React component rendered within the matching route.
import { useParams } from "react-router";
function UserProfile() {
const params = useParams();
return <h2>User ID: {params.userId}</h2>;
}
export default UserProfile;
You can also use object destructuring to retrieve the required parameter directly.
const { userId } = useParams();
Both approaches retrieve the same parameter value.
6. Example: Displaying a User ID
Step 1: Create UserProfile.jsx
import { useParams } from "react-router";
function UserProfile() {
const { userId } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>Selected User ID: {userId}</p>
</div>
);
}
export default UserProfile;
Step 2: Define the Route in App.jsx
import { Routes, Route } from "react-router";
import UserProfile from "./UserProfile.jsx";
function App() {
return (
<Routes>
<Route path="/users/:userId" element={<UserProfile />} />
</Routes>
);
}
export default App;
Step 3: Test the URL
Open /users/25 in the browser. The component displays:
User Profile
Selected User ID: 25
If you open /users/80, the same component displays User ID: 80.
7. Understanding Dynamic Route Parameters
Dynamic route parameters are created by adding a colon before a segment name in the route path.
<Route path="/products/:productId" element={<ProductDetails />} />
Here, :productId is the parameter name. The value is supplied by the URL.
| Route Pattern |
Current URL |
useParams Result |
/products/:productId |
/products/101 |
{`{ productId: "101" }`} |
/users/:userId |
/users/25 |
{`{ userId: "25" }`} |
/posts/:slug |
/posts/react-basics |
{`{ slug: "react-basics" }`} |
Parameter values are normally strings, even when they contain only digits.
8. Using Multiple Parameters with useParams()
A route can contain multiple dynamic parameters. The useParams hook returns all parameters matched by the current route.
Route Definition
<Route
path="/categories/:categoryId/products/:productId"
element={<ProductDetails />}
/>
Component Example
import { useParams } from "react-router";
function ProductDetails() {
const { categoryId, productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Category ID: {categoryId}</p>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetails;
For the URL /categories/5/products/101, the hook returns values equivalent to {`{ categoryId: "5", productId: "101" }`}.
9. Complete Example: Product Listing and Details
This example shows how useParams can retrieve a product ID and display the corresponding product from an array.
import { Routes, Route, Link, useParams } from "react-router";
const products = [
{ id: "101", name: "Laptop", price: 55000 },
{ id: "102", name: "Mobile Phone", price: 25000 },
{ id: "103", name: "Headphones", price: 2000 }
];
function ProductList() {
return (
<div>
<h1>Products</h1>
{products.map((product) => (
<p key={product.id}>
<Link to={`/products/${product.id}`}>
{product.name}
</Link>
</p>
))}
</div>
);
}
function ProductDetails() {
const { productId } = useParams();
const product = products.find((item) => item.id === productId);
if (!product) {
return <h2>Product Not Found</h2>;
}
return (
<div>
<h1>{product.name}</h1>
<p>Product ID: {product.id}</p>
<p>Price: ₹{product.price}</p>
<Link to="/">Back to Products</Link>
</div>
);
}
export default function App() {
return (
<Routes>
<Route path="/" element={<ProductList />} />
<Route path="/products/:productId" element={<ProductDetails />} />
</Routes>
);
}
How It Works
- The ProductList component displays the available products.
- Each Link navigates to a URL containing the selected product ID.
- React Router matches the dynamic route.
- useParams retrieves the productId value.
- The ProductDetails component finds and displays the matching product.
- If the ID does not match a product, a Product Not Found message appears.
10. Using useParams with API Data
In real applications, route parameters are often used to request data from an API. For example, a product ID can identify which product the application should fetch.
The following example uses the Fetch API inside a React effect. Replace the sample API endpoint with an endpoint from your application.
import { useEffect, useState } from "react";
import { useParams } from "react-router";
function ProductDetails() {
const { productId } = useParams();
const [product, setProduct] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function loadProduct() {
setLoading(true);
setError("");
setProduct(null);
try {
const response = await fetch(
`/api/products/${encodeURIComponent(productId)}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Unable to load product.");
}
const data = await response.json();
setProduct(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong.");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
loadProduct();
return () => controller.abort();
}, [productId]);
if (loading) return <p>Loading product...</p>;
if (error) return <p>{error}</p>;
if (!product) return <p>Product not found.</p>;
return (
<div>
<h2>{product.name}</h2>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetails;
Important: This example assumes the API returns a product object with a name field. The endpoint, response structure, and error handling should be adjusted to your backend. The effect runs again when productId changes, and the cleanup helps cancel an outdated request.
11. useParams vs useSearchParams
React Router provides different hooks for reading different parts of the URL.
| Feature |
useParams() |
useSearchParams() |
| Reads |
Dynamic route parameters. |
Query string parameters. |
| Example URL |
/products/101 |
/products?category=phones |
| Example value |
productId = "101" |
category = "phones" |
| Typical use |
Identifying a specific resource. |
Search, filtering, sorting, or pagination. |
Example of useSearchParams()
import { useSearchParams } from "react-router";
function ProductSearch() {
const [searchParams] = useSearchParams();
const category = searchParams.get("category");
return <p>Category: {category}</p>;
}
export default ProductSearch;
For /products?category=phones, useSearchParams reads the query parameter category. This is different from a dynamic route parameter.
12. Reading Catch-All Parameters
React Router supports catch-all route segments using an asterisk (*). The matched remainder of the path is available from useParams under the key "*".
Route Definition
<Route path="/files/*" element={<FileViewer />} />
Component Example
import { useParams } from "react-router";
function FileViewer() {
const params = useParams();
const filePath = params["*"];
return <p>Requested file path: {filePath}</p>;
}
export default FileViewer;
For a URL such as /files/documents/report.pdf, the captured remainder is documents/report.pdf.
13. Important Rules and Best Practices
- Call useParams at the top level of a React component or custom hook, not inside loops or conditions.
- Use it inside a component rendered within a suitable React Router route context.
- Make sure the parameter name matches the dynamic segment defined in the route path.
- Remember that route parameter values are normally strings.
- Convert numeric parameters using
Number() when required, and validate the result.
- Handle invalid IDs and missing records with a clear message or error page.
- Use parameters to select data or request it from an API; useParams does not fetch data automatically.
- Validate and authorize sensitive operations on the server as well as checking values in the frontend.
- Avoid placing passwords, tokens, or other secrets in URLs.
14. Common Mistakes and Solutions
| Mistake |
Solution |
| Forgetting the colon in a dynamic route. |
Use a pattern such as /users/:userId. |
| Using the wrong parameter name. |
Match the name in useParams with the route definition. |
| Expecting a numeric value automatically. |
Convert the string to a number and validate it. |
| Calling useParams outside a routed component. |
Render the component within the appropriate router and matched route context. |
| Assuming useParams fetches data. |
Implement data selection or API fetching separately. |
| Not handling unknown IDs. |
Display a not-found message or suitable error state. |
| Using useParams for query string values. |
Use useSearchParams for values after the question mark. |
15. Real-World Applications
- E-commerce: Display details for a selected product.
- Education portals: Retrieve a student's information using a student ID.
- Blog websites: Display an article based on its slug or ID.
- User management: Load a profile for a selected user.
- Order management: Display the details of a particular order.
- Travel applications: Display information for a selected destination.
16. Interview Questions and Answers
Q1. What is useParams in React Router?
useParams is a hook that returns an object containing dynamic parameters matched by the current route.
Q2. How do you import useParams?
In the current declarative API, import it using import { useParams } from "react-router";.
Q3. How do you define a dynamic route parameter?
Use a colon-prefixed segment, such as /users/:userId.
Q4. What does useParams return?
It returns an object containing the matched route parameters. Their values are normally strings.
Q5. Can useParams return multiple parameters?
Yes. A route such as /posts/:postId/comments/:commentId provides both postId and commentId.
Q6. Does useParams fetch API data?
No. It only reads route parameters. You must implement data fetching or lookup separately.
Q7. What is the difference between useParams and useSearchParams?
useParams reads dynamic segments from the URL path, while useSearchParams reads query string values.
Q8. Why should route parameters be validated?
Users can change URL values manually. Validation helps handle invalid inputs, and server-side checks are still necessary for security and authorization.
17. Practice Exercises
- Create a React application and install React Router.
- Set up BrowserRouter, Routes, and Route.
- Create a user profile route using
/users/:userId.
- Use useParams to display the selected user ID.
- Create a product details route using
/products/:productId.
- Display product information based on the selected ID.
- Create a route containing two dynamic parameters.
- Display an error message for an invalid or missing record.
- Read a query string using useSearchParams and compare it with useParams.
18. Quick Revision Checklist
- Understand the purpose of useParams.
- Know how to import and call the hook.
- Understand colon-prefixed dynamic route segments.
- Practice destructuring one or multiple parameters.
- Remember that parameter values are normally strings.
- Know how to use parameters in data lookups and API requests.
- Understand the difference between route and query parameters.
- Validate values and handle missing records.
19. Official Documentation and Course Links
Conclusion
The useParams hook is an important React Router tool for reading dynamic values from the current URL. By combining useParams with Routes, Route, and Link, developers can create reusable pages for products, users, posts, and other records. Understanding parameter names, string values, validation, and data fetching helps you build reliable, data-driven React applications.