ReactEasy

What are params?

Params (route parameters) are the dynamic parts of a URL path defined by a route pattern, such as :userId in /users/:userId. The router extracts them into an object, { userId: "42" } for /users/42, which components read with useParams() and loaders or actions receive as params.

Details

  • Values are always strings (or undefined for optional segments). Convert and validate: Number(params.id).
  • Names come from the route pattern: :projectId becomes params.projectId.
  • Splat routes (files/*) put the rest of the path in params["*"].
  • Nested routes see params from all matched parent routes.
  • In React Router framework mode, generated types make params typed per route.

Params vs query strings

  • Params: identify a resource, required for the route: /products/42.
  • Query strings: optional modifiers: /products?sort=price&page=2, read with useSearchParams().

Building URLs with params

Use generatePath("/users/:id", { id }) or template strings with encodeURIComponent for user-provided values.

Next.js

Dynamic segments like [slug] arrive as the params prop of pages and layouts. It is a Promise since Next.js 15, so you await params.

Common bug

Using params as React keys or effect dependencies is fine; mutating them or assuming they are numbers is not.

Code example

tsx
1import { generatePath, Link, useParams } from "react-router";
2
3export function TaskPage() {
4 const { projectId, taskId } = useParams(); // from /projects/:projectId/tasks/:taskId
5 const id = Number(taskId);
6
7 if (!projectId || Number.isNaN(id)) return <p>Invalid task URL</p>;
8
9 const next = generatePath("/projects/:projectId/tasks/:taskId", { projectId, taskId: String(id + 1) });
10
11 return (
12 <article>
13 <h1>Project {projectId}, task #{id}</h1>
14 <Link to={next}>Next task</Link>
15 </article>
16 );
17}
18
19// Route definition:
20// { path: "/projects/:projectId/tasks/:taskId", Component: TaskPage,
21// loader: ({ params }) => fetch(`/api/projects/${params.projectId}/tasks/${params.taskId}`) }

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.

Open in study app