Sub topic 7
Dynamic segments and useParams
This chapter assumes you can define route objects with createBrowserRouter, render links with Link and NavLink, and write React function components with hooks. It covers how one route can match many URLs and how a component reads the changing part of the URL.
What a dynamic segment is
A static route such as /about matches one URL. A user profile page needs to match /users/1, /users/2, and so on, without a route object for each user. A dynamic segment solves this. It is a path segment that starts with a colon, such as :userId. The router matches any single non-empty segment in that position and stores the matched text under the name you chose.
{ path: "users/:userId", element: <User /> }This route matches /users/42 and /users/ada. It does not match /users or /users/42/posts, because the number of segments differs.
Reading params with useParams
useParams is a hook that returns an object of the dynamic values matched by the current route and its parents. The keys are the names you wrote 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>
);
}UserLink builds the URL with a template string. NavLink passes isActive to the className function, so the link for the current user can be styled.
The diagram shows how a URL becomes a param.
Common errors
- Params are strings.
userIdis"42", not42. Comparing it with===to a number always fails. Convert it withNumber(userId)when you need a number. - Name mismatch. If the route says
:userIdand you destructureid, you getundefined. The names must match exactly. - Encoded values. The router decodes the segment, so
/users/a%20bgives"a b". Encode values when you build links, for example withencodeURIComponent(name). - Same component, new param. Going from
/users/1to/users/2keeps the sameUserinstance mounted. It re-renders with a newuserId. State set withuseStateis not reset. An effect that fetches data must listuserIdin its dependency array.
Params in loaders
A loader runs outside any component, so it cannot call hooks. The router passes it the same values as a params property of its argument.
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.userId}`);
return res.json();
}Chapter on loaders covers this in more detail. For now, note that params.userId here is the same string useParams would return.
Exercise
A route is defined as { path: "posts/:postId/comments/:commentId", element: <Comment /> }. Write the line that reads both values inside Comment, and say what type each value has.
Show answer
const { postId, commentId } = useParams(); Both values are strings, even if the URL contains digits such as /posts/7/comments/3. Convert them with Number(...) if you need numbers.