What is useParams hook?
The `useParams` hook is a powerful feature provided by React Router Dom, designed to help React components access and utilize URL parameters defined in a route. It's essential for building dynamic applications where specific data or views are determined by segments of the URL.
What is useParams?
useParams is a hook from the react-router-dom library that allows you to extract dynamic parameters from the URL. When a route path contains segments like :id, :category, or :slug, useParams provides these values as an object within your functional component.
It returns an object where keys are the parameter names (as defined in your route path) and values are the corresponding parts of the URL.
How it Works
To use useParams, you first need to define a route with dynamic segments using the colon (:) prefix in your Router setup.
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/users/:userId" element={<UserProfile />} />
<Route path="/products/:category/:productId" element={<ProductDetail />} />
<Route path="/posts/:slug" element={<BlogPost />} />
</Routes>
</Router>
);
}
Then, within the component rendered by that route (UserProfile, ProductDetail, BlogPost in the example), you can call useParams to get the parameter values.
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return (
<div>
<h2>User Profile</h2>
<p>User ID: {userId}</p>
{/* Fetch user data using userId */}
</div>
);
}
function ProductDetail() {
const { category, productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Category: {category}</p>
<p>Product ID: {productId}</p>
{/* Fetch product data using category and productId */}
</div>
);
}
Key Characteristics
- Dynamic URLs: Enables creation of routes that adapt to changing data, like
/users/1,/users/2, etc. - Object Return: Always returns an object, even if no parameters are present (it will be an empty object
{}). - Requires Matching Route:
useParamsonly works when the current URL path matches a route that has defined dynamic segments. - Type: It's a React Hook, meaning it can only be called inside functional components or custom hooks.
- Context-aware: It automatically gets the parameters relevant to the currently rendered component based on its position in the route tree.
When to Use It
useParams is indispensable in scenarios where you need to display specific content based on an identifier or slug present in the URL. Common use cases include:
- Displaying details for a specific item (e.g., product, user, article) from a list.
- Implementing user profile pages based on a user ID.
- Categorizing content and showing items within a specific category.
- Building dashboards where sub-sections are identified by URL parameters.