Onjsdev

Share


React Router useParams Hook


By onjsdev

Nov 8th, 2023

The React Router useParams hook enables to access dynamic parameters in URL so that these parameters can be used within components for different purposes such as fetching, filtering, and others.

In this article, we will cover the useParams hook and explore its usage with examples.

Understanding Dynamic Routes With Parameters

Imagine there are thousands of products listed on an e-commerce site. It is impossible to manually create routes such as product/1, product/23 for each product. That's why we need dynamic routes.

Dynamic routes are routes that can accept unique parameters. For example, in this e-commerce website, you may have a route like /products/:id, where :id represents the unique identifier of a product. When a user visits a specific product page matching this pattern, the id parameter in the URL can be captured and used to fetch the corresponding product data.

Setting Routes

Now, let's set both a dynamic and static routes. To define routes in React Router v6, BrowserRouter, Route and Routes packages is imported from the react-router-dom package. Then, each route is created with its path and element as shown the following example:

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import Home from './components/Home';
import UserProfile from './components/UserProfile';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </Router>
  );
}

export default App;

In the code above, there is a route, /users/:userId, that includes a parameter :userId. This means that the route expects a dynamic value for the userId parameter. At this point, useParams hook comes into play to retrieve the dynamic part of the route.

React Router useParams

The useParams hook is a built-in hook provided by React Router. To use the useParams hook, you need to import it from the react-router-dom package:

import { useParams } from 'react-router-dom';

Access route params

The :userId parameter represents the unique identifier of a user. To access this parameter within a component, you can use the useParams hook as follows:

import { useParams } from 'react-router-dom';

function UserPage() {
  const { userId } = useParams();

  // Rest of the component logic

  return (
    <div>
      <h2>User ID: {userId}</h2>
      {/* Render user information */}
    </div>
  );
}

The returned object from useParams contains key-value pairs, where the key corresponds to the parameter name defined in the route and the value represents the actual parameter value. For example, if someone visit the URL /user/12, the hook will return the following object:

{
  userId:12 
}

Thus, for example, for a user with an id of 12, you can request the API or your backend server to obtain the user's information and render it on the page.

Access multiple route params

In cases where you have multiple parameters defined in our route, you can access them using separate variables or by using object destructuring. Let's consider a route like /users/:userId/posts/:postId, where we have two parameters: userId and postId.

import { useParams } from 'react-router-dom';

function PostPage() {
  const { userId, postId } = useParams();

  // Rest of the component logic

  return (
    <div>
      <h2>User ID: {userId}</h2>
      <h2>Post ID: {postId}</h2>
      {/* Render post information */}
    </div>
  );
}

Again, we use object destructuring to extract both userId and postId parameters from the URL. We can then use these values within our component to display the relevant information.

useParams Hook With Typescript

If you have TypeScript set up in your project, Here's an example of how to use the useParams hook with TypeScript.

import React from 'react';
import { useParams } from 'react-router-dom';

interface Params {
  userId: string;
}

const UserProfile: React.FC = () => {
  const { userId } = useParams<Params>();

  return (
    <div>
      <h2>User Profile</h2>
      <h2>User ID: {userId}</h2>
      {/* Render user profile information */}
    </div>
  );
};

export default UserProfile;

In this example, we define an interface Params that represents the structure of the route parameters. In this case, we have a single parameter userId of type string. We then use this interface as a type to the useParams hook so that it provides type safety.

Conclusion

React Router useParams hook is used for handling dynamic route parameters in React applications. With the help of this hook, you can easily access and use whether a single parameter or multiple parameters from the URL within components so that you can use them for fetching and filtering.

Thank you for reading