How to Use useParams Hook in React Router
This article provides a quick and straightforward guide on how to
implement and use the useParams hook in React Router. You
will learn how to configure dynamic routes, extract URL parameters
within your components, and apply this hook to handle dynamic routing in
your React applications.
What is the useParams Hook?
The useParams hook is a built-in feature of the
react-router-dom library. It allows you to access the
dynamic parameters (slugs or IDs) from the current URL. This is
essential for building dynamic pages, such as user profiles, product
detail pages, or blog posts, where the content changes based on the
URL.
Step 1: Install React Router
Before using useParams, ensure you have
react-router-dom installed in your project. If you haven’t
installed it yet, run the following command in your terminal:
npm install react-router-domStep 2: Define a Route with Parameters
To use useParams, you first need to define a route with
a path variable. Path variables are prefixed with a colon
(:) in your route definition.
Here is how you set up the routing in your main application file
(e.g., App.js):
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<Router>
<Routes>
{/* The ":id" acts as a placeholder for the dynamic parameter */}
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
</Router>
);
}
export default App;Step 3: Implement useParams in Your Component
Now, you can extract the dynamic parameter within the component
rendered by that route (UserProfile). Import the
useParams hook from react-router-dom and call
it inside your component function.
Here is the implementation in UserProfile.js:
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
// Destructure the "id" parameter from useParams()
const { id } = useParams();
return (
<div style={{ padding: '20px' }}>
<h1>User Profile Page</h1>
<p>Currently viewing profile for User ID: <strong>{id}</strong></p>
</div>
);
}
export default UserProfile;How It Works
- When a user navigates to a URL like
/user/42, React Router matches the path/user/:id. - The value
42is automatically assigned to the keyid. - Inside the
UserProfilecomponent,useParams()returns an object:{ id: "42" }. - You can then use this destructured value to fetch data from an API, display it on the screen, or trigger other component logic.