Popular Searches
Popular Course Categories
Popular Courses

useParams Hook

useParams Hook

React Router

useParams Hook in React JS

The useParams Hook is a React Router Hook used to access dynamic parameters from the current URL. It allows developers to retrieve values such as product IDs, user IDs, usernames, blog post IDs, and category names directly inside a React component.

For example, if a user visits /products/101, React Router can extract 101 from the URL using useParams(). The component can then use this value to display the correct product details.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.


1. What Is the useParams Hook?

useParams() is a built-in Hook provided by React Router. It returns an object containing the dynamic route parameters that match the current URL.

Dynamic parameters are defined in a route using a colon (:) followed by a parameter name.

Example

import { BrowserRouter, Routes, Route } from "react-router";
import { useParams } from "react-router";
function ProductDetails() {
  const { productId } = useParams();
  return <h1>Product ID: {productId}</h1>;
}
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/products/:productId" element={<ProductDetails />} />
      </Routes>
    </BrowserRouter>
  );
}
export default App;

If the browser URL is /products/101, the page displays Product ID: 101.

Note: Import paths depend on the React Router version and project setup. Current React Router documentation uses imports from react-router; many existing browser-based projects use react-router-dom.


2. Why Do We Use useParams?

The useParams Hook is useful when a page needs to display information based on a value included in the URL. Instead of creating a separate route for every item, developers can create one dynamic route that handles many values.

  • Dynamic pages: Display different content based on the URL.
  • Product details: Retrieve a product ID from the URL.
  • User profiles: Display the profile associated with a username or user ID.
  • Blog applications: Retrieve a post ID or slug.
  • Category pages: Identify a selected category.
  • Nested routes: Access parameters inherited from parent routes.

3. Understanding Dynamic Route Parameters

A dynamic route parameter is a variable section of a URL. In React Router, it is represented by a colon followed by a parameter name.

Example route

<Route path="/users/:userId" element={<UserProfile />} />

In this example, :userId is the dynamic parameter. The same route can match multiple URLs.

URL Parameter name Parameter value
/users/10 userId 10
/users/25 userId 25
/users/100 userId 100

The component reads the value with const { userId } = useParams();. This avoids writing separate components or routes for every user.


4. Syntax of the useParams Hook

const params = useParams();

The returned object contains the parameters matched from the current route. You can access a parameter using dot notation or destructuring.

Using dot notation

const params = useParams();
console.log(params.productId);

Using object destructuring

const { productId } = useParams();
console.log(productId);

Destructuring is often preferred when you need only one or two parameters. The parameter values returned by React Router are generally strings, so convert them when numeric calculations are required.


5. Step-by-Step Implementation

Step 1: Install React Router

If React Router is not already installed in your project, install it using npm.

npm install react-router

For a project following an older React Router setup, you may see react-router-dom used instead. Follow the import paths supported by the installed version.

Step 2: Create a component

Create a file named ProductDetails.jsx and import the useParams Hook.

import { useParams } from "react-router";
function ProductDetails() {
  const { productId } = useParams();
  return (
    <div>
      <h2>Product Details</h2>
      <p>Selected Product ID: {productId}</p>
    </div>
  );
}
export default ProductDetails;

Step 3: Define a dynamic route

In your main application component, define a route that includes the parameter.

import { BrowserRouter, Routes, Route } from "react-router";
import ProductDetails from "./ProductDetails";
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/products/:productId" element={<ProductDetails />} />
      </Routes>
    </BrowserRouter>
  );
}
export default App;

Step 4: Test the URL

Open a matching URL in the browser, such as http://localhost:5173/products/101, assuming your development server is running on that address.

The component receives 101 as the value of productId and displays it on the page.


6. Using Multiple Route Parameters

A route can contain more than one dynamic parameter. Each parameter is identified by its own name and can be retrieved from the object returned by useParams.

Route example

<Route path="/users/:userId/posts/:postId" element={<PostDetails />} />

Component example

import { useParams } from "react-router";
function PostDetails() {
  const { userId, postId } = useParams();
  return (
    <div>
      <h2>Post Details</h2>
      <p>User ID: {userId}</p>
      <p>Post ID: {postId}</p>
    </div>
  );
}
export default PostDetails;

For the URL /users/12/posts/45, the values are userId = "12" and postId = "45".


7. Using useParams to Display Product Information

In a shopping application, the product ID in the URL can be used to select a product from a local data collection. In a real application, the ID can also be used to request product details from an API.

import { 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 ProductDetails() {
  const { productId } = useParams();
  const product = products.find(item => item.id === productId);
  if (!product) {
    return <h2>Product not found</h2>;
  }
  return (
    <div>
      <h2>{product.name}</h2>
      <p>Product ID: {product.id}</p>
      <p>Price: ₹{product.price}</p>
    </div>
  );
}
export default ProductDetails;

When the URL is /products/102, the component displays the Mobile Phone details. The example uses local data; an API-based application would fetch the corresponding product from its backend.


8. Using useParams with API Requests

The parameter can be used to retrieve data from an API. For example, a product details page may request /api/products/101 when the browser URL is /products/101.

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("");
      try {
        const response = await fetch(
          `/api/products/${encodeURIComponent(productId)}`,
          { signal: controller.signal }
        );
        if (!response.ok) {
          throw new Error("Unable to load product details.");
        }
        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>Price: ₹{product.price}</p>
    </div>
  );
}
export default ProductDetails;

Important: This example assumes your backend exposes the API endpoint and returns the expected JSON structure. The abort controller helps cancel an outdated request when the parameter changes or the component unmounts.


9. Difference Between useParams and useSearchParams

Both Hooks read values associated with a URL, but they handle different parts of it.

Feature useParams useSearchParams
Reads Dynamic path parameters Query-string parameters
Example URL /products/101 /products?category=books
Example value productId = "101" category = "books"
Typical use Identify a specific resource Filters, search terms, sorting, pagination

useParams example

const { productId } = useParams();

useSearchParams example

import { useSearchParams } from "react-router";
const [searchParams] = useSearchParams();
const category = searchParams.get("category");

10. Important Rules and Best Practices

  • Use a matching route: Define the dynamic parameter in the route path, such as :productId.
  • Match parameter names: If the route uses :userId, read userId, not id.
  • Remember the value type: Route parameters are normally strings. Use Number() when a numeric value is required and validate the result.
  • Handle missing data: Display a suitable message when the requested item does not exist.
  • Keep Hooks at the top level: Call useParams inside a React function component or a custom Hook, not inside loops or conditions.
  • Use effects for API requests: If a parameter drives a request, include it in the effect dependency array.
  • Encode values when constructing URLs: Use encodeURIComponent() for values inserted into a URL path where appropriate.
  • Do not treat a URL ID as authorization: A backend must verify access permissions for protected resources.
  • Know your Router version: Use the import paths and routing conventions supported by your installed React Router version.

11. Common Mistakes and Solutions

Mistake Why it happens Solution
Parameter is undefined The route parameter name does not match the component code. Check the route path and destructured property name.
Hook is used outside a routed component The component is not rendered within the appropriate Router context. Render the component under the configured Router and matched route.
Comparing a string ID with a number Route values are strings. Normalize the types before comparison.
Page shows no product The parameter does not match any record. Check the ID and display a not-found message.
API data does not update The effect does not depend on the changing parameter. Add the parameter to the effect dependency array.
Import error The code uses a different package path from the installed version. Check the installed React Router version and its documentation.

12. Mini Project: User Profile Page

Objective: Build a simple user profile page that displays different users based on the ID in the URL.

App.jsx

import { BrowserRouter, Routes, Route } from "react-router";
import UserProfile from "./UserProfile";
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </BrowserRouter>
  );
}
export default App;

UserProfile.jsx

import { useParams } from "react-router";
const users = {
  "1": { name: "Aarav", role: "Frontend Developer" },
  "2": { name: "Diya", role: "UI Designer" },
  "3": { name: "Kabir", role: "Backend Developer" }
};
function UserProfile() {
  const { userId } = useParams();
  const user = users[userId];
  if (!user) {
    return <h2>User not found</h2>;
  }
  return (
    <div>
      <h1>User Profile</h1>
      <p>ID: {userId}</p>
      <p>Name: {user.name}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}
export default UserProfile;

Test the project

  • Visit /users/1 to display Aarav's profile.
  • Visit /users/2 to display Diya's profile.
  • Visit /users/3 to display Kabir's profile.
  • Visit /users/99 to see the User not found message.

Expected learning outcomes

  • Define dynamic route parameters.
  • Access URL values using useParams.
  • Display data based on a route parameter.
  • Handle invalid IDs and missing records.

13. Interview Questions and Answers

Q1. What is the useParams Hook?

Answer: useParams is a React Router Hook that returns an object containing dynamic parameters from the currently matched route.

Q2. Why do we use useParams?

Answer: It allows a component to read values such as IDs or slugs from a URL and use them to display or retrieve relevant data.

Q3. How do you define a dynamic route parameter?

Answer: Add a colon before the parameter name in the route path, for example /products/:productId.

Q4. What does useParams return?

Answer: It returns an object whose properties correspond to the dynamic parameters matched from the current URL.

Q5. Are useParams values strings or numbers?

Answer: They are normally strings. Convert and validate a value if the application needs a number.

Q6. Can a route contain multiple parameters?

Answer: Yes. For example, /users/:userId/posts/:postId provides both userId and postId.

Q7. Can useParams access query-string values?

Answer: No. Query-string values such as ?category=books are typically read using useSearchParams().

Q8. Can useParams be used in a regular JavaScript function outside a component?

Answer: No. Like other React Hooks, it must be called at the top level of a React function component or a custom Hook, within the appropriate Router context.

Q9. What happens if the parameter does not match a data record?

Answer: The application should handle the missing record and display a not-found message or another suitable fallback.

Q10. Can nested routes access parent route parameters?

Answer: Yes. Child routes inherit parameters from their parent routes.


14. Practice Exercises

  1. Create a route /students/:studentId and display the student ID.
  2. Create a route /courses/:courseId and show the course title from a local array.
  3. Create a route /categories/:categoryId/products/:productId and display both parameter values.
  4. Build a blog details page using /blog/:postId.
  5. Use a route parameter to request data from an API and show loading, error, and success states.

15. Quick Revision Checklist

  • Understand what useParams does.
  • Know how to define a dynamic route using :parameterName.
  • Know how to import and call useParams.
  • Understand object destructuring and dot notation.
  • Retrieve multiple route parameters.
  • Remember that route parameter values are normally strings.
  • Distinguish path parameters from query-string parameters.
  • Handle invalid IDs, missing data, and API errors.
  • Understand that nested routes inherit parent parameters.

16. Conclusion

The useParams Hook is an important React Router feature for creating dynamic, reusable pages. It helps applications read values from the URL and use those values to show specific products, user profiles, blog posts, and other resources. By practising dynamic routes, multiple parameters, API requests, and error handling, developers can build more flexible React applications.

To continue learning React JS, visit JustAcademy React JS Training. You can also Register for React JS Course Demo.

Official Reference

Previous Next
whatsapp