Sub topic 7
Dynamic segments and useParams
This chapter assumes you can write React function components and hooks, and that you have a data router set up with createBrowserRouter and RouterProvider. You should also know how route objects and nested routes work. Here you will learn how to match a variable part of a URL and read it in your components and loaders.
Why dynamic segments exist
A static path such as /about matches one URL. Many pages are the same view for different records, such as /users/1, /users/2 and /users/987. You do not want to write one route per user.
A dynamic segment is a part of a path that starts with a colon, such as :userId. It matches any single non-empty piece of the URL at that position. The router stores the matched text in an object called the params, keyed by the name after the colon.
import { useParams, NavLink } from "react-router-dom";
// Route definition: { path: "users/:userId", element: <User /> }
function User() {
const { userId } = useParams();
return <h1>User {userId}</h1>;
}
function UserLink({ id }) {
return (
<NavLink
to={`/users/${id}`}
className={({ isActive }) => (isActive ? "active" : undefined)}
>
User {id}
</NavLink>
);
}For the URL /users/42, useParams() returns { userId: "42" }. NavLink builds the link for each user, and its isActive flag marks the link that matches the current URL.
How matching works
The router compares the URL path to each route's path, segment by segment. A segment is the text between slashes.
- A static segment such as
usersmust match exactly. - A dynamic segment such as
:userIdmatches any one segment. It does not match an empty segment, and it does not match text that contains a slash. - Matching is case-insensitive by default.
- If several routes could match, the router ranks them. A static segment beats a dynamic one, and a dynamic one beats a splat (
*). Order in the array does not decide the winner.
This ranking lets a specific route sit next to a dynamic one:
import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/users",
children: [
{ index: true, element: <h1>All users</h1> },
{ path: "new", element: <h1>New user</h1> },
{ path: ":userId", element: <h1>One user</h1> },
],
},
]);The URL /users/new renders "New user", because the static new segment outranks :userId. The URL /users/42 renders "One user".
Reading params with useParams
useParams is a hook that returns an object of the dynamic segments for the current route and its parent routes. Parents come into play because nested routes build on each other's paths.
import { useParams } from "react-router-dom";
// Routes:
// { path: "teams/:teamId", element: <Team />, children: [
// { path: "members/:memberId", element: <Member /> }
// ] }
function Member() {
const { teamId, memberId } = useParams();
return (
<p>
Member {memberId} of team {teamId}
</p>
);
}For /teams/7/members/3, Member sees both teamId and memberId. A component rendered by a parent route sees only the params that exist at its level and above. It cannot see memberId, because that segment belongs to the child.
Params are always strings
Every value in the params object is a string, even when it looks like a number. "42" === 42 is false, so convert values before you compare them or use them as numbers.
import { useParams } from "react-router-dom";
function Invoice({ invoices }) {
const { invoiceId } = useParams();
const id = Number(invoiceId);
const invoice = invoices.find((item) => item.id === id);
if (Number.isNaN(id) || !invoice) {
return <p>Invoice not found.</p>;
}
return <h1>Invoice {invoice.number}</h1>;
}Number("abc") is NaN, so the check handles URLs that a user typed by hand.
Params can be missing in your types
If you use TypeScript, each param has the type string | undefined. Nothing in the path guarantees that a name exists, because useParams does not know which route is rendering your component. In plain JavaScript you get undefined when you read a name that is not in the path. A misspelled name fails silently, so check that the name in useParams matches the name after the colon exactly.
Optional segments, splats, and encoding
A trailing ? marks a segment as optional.
const route = { path: "products/:category?", element: <Products /> };This route matches /products and /products/shoes. When the segment is absent, category is undefined.
A splat route uses * at the end of a path and captures the rest of the URL. Its value lives under the key "*".
import { useParams } from "react-router-dom";
// Route definition: { path: "files/*", element: <FileViewer /> }
function FileViewer() {
const params = useParams();
const filePath = params["*"];
return <p>Viewing {filePath}</p>;
}For /files/docs/guide/intro.md, params["*"] is "docs/guide/intro.md".
The router decodes URL-encoded text for you. A URL ending in /users/a%20b gives userId the value "a b". When you build a link from user input, encode the value so that special characters cannot change the path.
import { Link } from "react-router-dom";
function SearchResult({ name }) {
return <Link to={`/users/${encodeURIComponent(name)}`}>{name}</Link>;
}Without encodeURIComponent, a name such as a/b would add an extra segment and fail to match users/:userId.
Params in loaders
Components are not the only place to read params. A loader receives them in its argument, so it can fetch data before the route renders. Loaders are covered fully in a later chapter, but the param access is the same idea.
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.userId}`);
if (!res.ok) {
throw new Response("User not found", { status: res.status });
}
return res.json();
}Actions receive params in the same way. Inside a loader you cannot call hooks, so params from the argument is the only way to get the segments there.
When the param changes but the route does not
Navigating from /users/1 to /users/2 does not unmount the User component. The route is the same, only its params differ, so React keeps the component instance and re-renders it with the new values. This has two consequences.
- State inside the component survives the change. A form field the user typed in on
/users/1is still there on/users/2. - An effect that fetches data must list the param in its dependency array, or it will not run again.
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
function User() {
const { userId } = useParams();
const [user, setUser] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => res.json())
.then(setUser)
.catch((error) => {
if (error.name !== "AbortError") throw error;
});
return () => controller.abort();
}, [userId]);
return <h1>{user ? user.name : "Loading..."}</h1>;
}The cleanup function aborts the old request, so a slow response for user 1 cannot overwrite the result for user 2. A loader avoids this problem, because the router reruns it when the params change and discards stale results for you.
If you want state to reset when the param changes, give the component a key. A wrapper can read the param and pass it as the key:
import { useParams } from "react-router-dom";
function UserPage() {
const { userId } = useParams();
return <UserEditor key={userId} />;
}When key changes, React discards the old UserEditor and creates a new one with fresh state.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Name mismatch between path and hook | `undefined` value | Use the exact name from the path, such as `userId` |
| Comparing a param to a number | Lookup finds nothing | Convert with `Number(...)` |
| Leading colon missing in the path | Route matches only the literal text | Write `:userId`, not `userId` |
| Effect without the param in dependencies | Stale data after navigation | Add the param to the dependency array, or use a loader |
| Unencoded user text in a link | Wrong route or no match | Wrap it in `encodeURIComponent` |
How it fits together
The diagram shows the path from a URL to the value your code reads.
Exercise
A route is defined as { path: "posts/:postId", element: <Post /> }. Inside Post, you call useParams() and the user visits /posts/15. Write the line that gives you the post id as a number, and explain why the extra conversion is needed.
Show answer
const postId = Number(useParams().postId); (or destructure postId first, then call Number(postId)). The value is "15", a string, because every param is a string. A strict comparison with a numeric id such as 15 would be false without the conversion.
Exercise
A page has the routes users/new and users/:userId. A user opens /users/new. Which route renders, and does the order of the two routes in the array change that?
Show answer
The users/new route renders. The router ranks a static segment above a dynamic one, so the order in the array does not change the result.
Exercise
Users go from /users/1 to /users/2. The User component fetches data in useEffect with an empty dependency array. What goes wrong, and how do you fix it?
Show answer
The component stays mounted and re-renders with the new param, but the empty array means the effect never runs again, so it still shows user 1's data. Add userId to the dependency array, and abort the old request in the cleanup. Alternatively, move the fetch into a loader, which reruns when the params change.