InterviewHubPRO
Section Overview
Q347

Question 347 of 445

Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

78%
React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

What are dynamic routes and what are route parameters?

A dynamic route is a route path that contains a placeholder segment (a route parameter) instead of a fixed, hard-coded value, so a single route definition can match many different URLs. Route parameters are the named placeholder segments (prefixed with : in React Router) whose actual values are extracted from the matched URL at runtime.

jsx
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";

function UserProfile() {
// useParams() returns an object of all dynamic segments matched for this route
const { userId } = useParams();
return <div>Profile for user: {userId}</div>;
}

function App() {
return (
  <BrowserRouter>
    <Routes>
      {/* :userId is a route parameter — matches /users/1, /users/abc, etc. */}
      <Route path="/users/:userId" element={<UserProfile />} />
    </Routes>
  </BrowserRouter>
);
}

A route can also define multiple parameters and an optional catch-all (splat) parameter:

jsx
// Multiple params: /posts/2024/react-hooks-guide
<Route path="/posts/:year/:slug" element={<Post />} />

// Optional segment (v6.4+): matches /shop and /shop/electronics
<Route path="/shop/:category?" element={<Shop />} />

// Splat/wildcard param: matches any depth, e.g. /docs/a/b/c
<Route path="/docs/*" element={<Docs />} />
jsx
function Post() {
const { year, slug } = useParams();
// year -> "2024", slug -> "react-hooks-guide"
return <h1>{slug} ({year})</h1>;
}

Key points:

  • Route params are always returned as strings by useParams() — convert them (e.g., Number(id)) if you need a number.
  • Static routes (/about) are matched exactly; dynamic routes (/users/:userId) match a whole family of URLs and are essential for detail/edit pages, pagination, category filters, etc.
  • Route params are different from query/search params (?sort=asc), which are read with useSearchParams() instead and are meant for optional, non-hierarchical data like filters or sorting.
  • Because dynamic segments can match unexpected values, always validate/guard params (e.g., check the fetched resource exists) rather than assuming the value is always well-formed.