ReactEasy
What is useParams?
useParams() is a React Router hook that returns an object with the dynamic segment values of the current URL, matched against the route pattern. For a route /users/:userId and the URL /users/42, it returns { userId: "42" }. It includes params from parent routes, and splat values under "*".
Details
- Values are strings or
undefined; validate and convert them. - Re-renders the component when params change. The same component instance stays mounted when navigating from
/users/1to/users/2, so state persists; addkey={userId}on a child (or reset state) if each user should start fresh. - In loaders, actions and middleware, use the
paramsargument instead of the hook. - Typed params: in framework mode, generated route types give
params.userIdthe right type; in data mode, cast or validate.
Typical use
- Fetching data for the resource in an effect or with TanStack Query:
useQuery({ queryKey: ["user", userId], ... }). - Building related links.
- Highlighting the selected item in a list.
Pitfall
Fetching in an effect keyed on params without cleanup can show the wrong user if responses arrive out of order. Use a loader, a data library, or an ignore flag.
Next.js
useParams() from next/navigation in Client Components; Server Components read the awaited params prop.
Code example
tsx
1import { useParams, Link } from "react-router";2import { useQuery } from "@tanstack/react-query";34type User = { id: string; name: string; email: string };56export function UserProfile() {7 const { userId } = useParams(); // "42" for /users/4289 const { data: user, isPending, error } = useQuery({10 queryKey: ["user", userId],11 queryFn: async (): Promise<User> => {12 const res = await fetch(`/api/users/${userId}`);13 if (!res.ok) throw new Error("User not found");14 return res.json();15 },16 enabled: !!userId, // param may be undefined on optional routes17 });1819 if (isPending) return <p>Loading…</p>;20 if (error) return <p role="alert">{error.message}</p>;2122 return (23 <section>24 <h1>{user.name}</h1>25 <p>{user.email}</p>26 <Link to={`/users/${Number(userId) + 1}`}>Next user</Link>27 </section>28 );29}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.