What is useParams Hook in React?

The useParams hook is a powerful feature in React Router that allows developers to retrieve dynamic parameters from the current URL. This article provides a clear, straight-to-the-point guide on what the useParams hook is, why it is essential for dynamic routing, and how to implement it in your React applications with a simple code example.

Understanding useParams in React Router

When building modern web applications, you often need to render components based on specific identifiers in the URL, such as a product ID, a username, or a post slug (e.g., /users/123 or /products/laptop).

In React Router, these variable parts of the URL are called route parameters. The useParams hook is a built-in hook that returns an object of key-value pairs of these URL parameters, where the key is the parameter name defined in the route path, and the value is the actual value currently in the URL.

How to Use the useParams Hook

To use useParams, you must have react-router-dom installed and configured in your React application. Here is a step-by-step breakdown of how to implement it.

Step 1: Define a Dynamic Route

First, you need to define a route with a dynamic parameter in your main router setup. You define a dynamic parameter by prefixing it with a colon (:).

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

function App() {
  return (
    <Router>
      <Routes>
        {/* ":userId" is the dynamic parameter */}
        <Route path="/user/:userId" element={<UserProfile />} />
      </Routes>
    </Router>
  );
}

export default App;

Step 2: Retrieve the Parameter with useParams

Inside the component rendered by that route (in this case, UserProfile), you import and call the useParams hook to access the dynamic value.

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

function UserProfile() {
  // Destructure the "userId" parameter from the useParams object
  const { userId } = useParams();

  return (
    <div>
      <h1>User Profile Page</h1>
      <p>Now displaying data for User ID: <strong>{userId}</strong></p>
    </div>
  );
}

export default UserProfile;

If a user navigates to /user/99, the useParams() hook will return { userId: '99' }, and the component will render “Now displaying data for User ID: 99”.

Why Use the useParams Hook?