Nearby lessons

34 of 44

🛣️ React Router – Dynamic Routes with useParams

📌 What is useParams?

What is useParams Hook in React Router?

In a React app, sometimes we want to access the parameters of the current route (like id, username, etc.). In this case, the useParams hook comes into action.

The useParams hook is part of react-router-dom. It returns an object of key/value pairs of the dynamic parameters from the current URL matched by the <Route path>.

📌 What is useParams?

  • It is a hook from react-router-dom.
  • It returns an object containing dynamic URL parameters.
  • We can destructure the params for easy usage.
  • Useful for routes like /user/:id, /product/:pid, etc.

⚙️ Example – Accessing Route Params

Let’s create a dynamic route /user/:id and fetch the id parameter using useParams.

React Playground
import React from 'react';
import { Link } from 'react-router-dom';

function App() {
  return (
    <div>
      <h1>Welcome to Dynamic Routing</h1>
      <p>Click below to view user details:</p>
      <Link to="/user/101">User 101</Link>
      <br />
      <Link to="/user/202">User 202</Link>
    </div>
  );
}

export default App;

🧩 How useParams Works?

  • The route path /user/:id contains a dynamic segment :id.
  • When the URL is /user/101, useParams() returns { id: "101" }.
  • We can use this parameter to fetch data, display info, or perform actions.

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!React - useSearchParams Router Hooks