Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 50 ยท Params and Search Params

Dynamic Segments and useParams

Learn dynamic segments in React Router: :id params, optional segments, splats, decoding, TypeScript types and how to validate params safely.

Most real URLs contain data. /products/42 shows product 42, /users/ada/posts/hello-world shows one post by one user, and /files/docs/guide/intro.md shows a file at any depth. You cannot write a route for every possible product, so React Router lets a route pattern contain dynamic segments: placeholders that match any value and hand it to your component.

Two things make params easy to get wrong. First, they come from the address bar, so they are untrusted input, just like a form field. Second, they are always strings (or missing), never numbers. This lesson shows the pattern syntax, how to read params with useParams, how decoding works, how to type them, and how to validate them so a bad URL becomes a clean 400 or 404 instead of a crash. It assumes you know Routes and Matching.

Dynamic segments and useParams

A path segment that starts with a colon is dynamic. The text after the colon is the param name, and whatever the URL contains in that position becomes its value.

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

function ProductPage() {
  const { productId } = useParams();
  return <h1>Product {productId}</h1>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="products/:productId" element={<ProductPage />} />
      </Routes>
    </BrowserRouter>
  );
}

At /products/42, useParams() returns { productId: "42" }. The router matches products literally and puts 42 under the name productId.

flowchart LR
  U["URL<br/>/products/42"] --> R["Route path<br/>products/:productId"]
  R --> P["params<br/>{ productId: '42' }"]
  P --> C["useParams() in ProductPage"]

The URL is matched against the pattern; the dynamic parts become the params object.

Some rules to remember:

  • A dynamic segment matches one whole segment. You cannot write report-:id to match only part of a segment.
  • A pattern can have several params: users/:userId/posts/:slug. In nested routes, a child sees the params of all its parent routes as well as its own (see Nested Routes and Outlet).
  • Param names are yours to choose. Pick names that read well at the use site, such as productId rather than id, so a nested route does not shadow a parent's id.
  • The values are strings. useParams() is typed to give string | undefined for each one, because a pattern might not match, or the param might be optional.
  • Static segments win. When both users/new and users/:id exist, the real router ranks the static route higher, so /users/new never ends up in the dynamic route. The stand-in router in the demos does not rank; it uses the first match, so the demos list static routes first.

Optional segments and splats

Add a question mark to make a dynamic segment optional. The same route then matches with and without it:

JSX
<Route path=":lang?/about" element={<About />} />
// /about      -> params: {}                (lang is undefined)
// /fr/about   -> params: { lang: "fr" }

A splat, written *, matches everything that is left, including slashes. It must be the last part of the pattern, and its value is available as params["*"]:

JSX
<Route path="files/*" element={<FileBrowser />} />
// /files/docs/guide/intro.md -> params: { "*": "docs/guide/intro.md" }

Splats are ideal for file browsers, docs sites with deep paths, and catch-all 404 routes (see 404 Pages and Catch-All Routes). The "*" key is awkward to destructure, so rename it: const { "*": path } = useParams();.

Try the matcher

The first demo prints what the stand-in matcher does with a list of URLs, using the patterns below. The patterns are tried in order. Type your own path in the box to test it, for example /posts/2026/a%2Fb or /fr/about.

Param matching lab

Read the table row by row. /users/new stops at the first pattern because static routes come first, /about matches the optional-language pattern without a lang key, and /files/docs/guide/intro.md lands in the splat as one string. Three rows deserve a closer look at the next section: the percent-encoded ones.

Decoding and encoding

URLs can only contain a limited set of characters, so everything else is percent-encoded: a space becomes %20, a slash inside a value becomes %2F, and a percent sign becomes %25. React Router decodes param values for you. At /posts/2026/hello%20world, params.slug is "hello world", and 100%25-sure becomes 100%-sure (see the table).

If a value contains a broken escape sequence, such as the truncated %E0%A4%A in the table, decoding would throw. The router does not crash: it keeps the raw text instead. Your code should still treat such a value as unexpected and validate it.

The reverse direction is your job. When you build a URL from data, encode each dynamic piece with encodeURIComponent:

JSX
// Wrong if a tag can contain "/", "?" or "#"
<Link to={`/tags/${tag}`}>{tag}</Link>

// Right
<Link to={`/tags/${encodeURIComponent(tag)}`}>{tag}</Link>

For several params at once, generatePath fills in a pattern and encodes the values for you:

JSX
import { generatePath } from "react-router";

generatePath("/users/:userId/posts/:slug", { userId: "7", slug: "hello world" });
// "/users/7/posts/hello%20world"

Keeping patterns in one place and building links with generatePath also protects you from typos when a URL structure changes.

Typing params

In plain TypeScript you pass the param names to useParams as a type argument:

TSX
import { useParams } from "react-router";

function ProductPage() {
  const { productId } = useParams<"productId">();
  // productId: string | undefined
}

Every value stays string | undefined, so you must handle undefined yourself. In framework mode the router generates exact types from your route file, so the same param is a plain string and an optional param is string | undefined:

TSX
import type { Route } from "./+types/product";

export default function Product({ params }: Route.ComponentProps) {
  return <h1>Product {params.productId}</h1>;
}

Types describe the shape of the URL, not its meaning. A string that must be a number is still a string, so you still validate it.

Validating params

The URL is user input. Anyone can type /products/abc, /products/-5 or /products/99999999. A good route does two checks, in order, and reports them differently:

  1. Is the value well formed? abc is not an id at all. That is a client error, a 400-style problem: "this address makes no sense".
  2. Does the thing exist? 99999999 is a valid id, but there is no such product. That is a 404.
flowchart TD
  A["param from the URL"] --> B{"well formed?<br/>digits only"}
  B -- no --> C["400: invalid id"]
  B -- yes --> D{"found in data?"}
  D -- no --> E["404: not found"]
  D -- yes --> F["render the page"]

Check the shape first, then check that the record exists.

Prefer a strict test over Number(value). Number("") is 0, Number("1e3") is 1000 and Number(" 7 ") is 7, and none of those are ids you want to accept. A regular expression such as /^\d+$/ says exactly what you mean. In data mode you do this in a loader and throw a Response, so the route's error element renders the problem (see Loaders and Error Boundaries and Error Elements):

JSX
export async function loader({ params }) {
  if (!/^\d+$/.test(params.productId ?? "")) {
    throw new Response("Invalid product id", { status: 400 });
  }
  const product = await getProduct(Number(params.productId));
  if (!product) {
    throw new Response("Not found", { status: 404 });
  }
  return product;
}

Never put a param into a SQL string, a file path or dangerouslySetInnerHTML without validating and escaping it. A splat such as ../../etc is a classic path-traversal attempt when it reaches a file system on a server.

A validated product page and a splat

The second demo builds the two checks into a component, and adds a splat route that renders breadcrumb links. Each breadcrumb target is built with encodeURIComponent. Try the "bad" product links and compare the messages.

Validated params and a splat route

Click "product abc": the id fails the shape check and you see the 400 message. "product 99" has a valid shape but no record, so you see the 404 message. In the file browser, the splat arrives as one decoded string ("my notes/todo.txt"), and the breadcrumb links re-encode each piece so the space survives the round trip.

Common mistakes

  • Treating params as numbers. params.id === 5 is never true, because params.id is "5". Convert after validating.
  • Forgetting that params can be undefined. Optional segments and splats can be missing. Give them a default or handle the case.
  • Skipping the 404. A well-formed id that does not exist is the most common case in practice. Plan for it first.
  • Building URLs from raw strings. Always encode user-controlled pieces, or use generatePath.
  • Naming every param id. In nested routes the names should be unique (projectId, taskId).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does useParams() return at /products/42 for the route products/:productId?

    The param name comes from the pattern (productId) and the value is always a string, here "42". Convert it yourself if you need a number.
  2. 2. Which pattern matches both /about and /fr/about?

    The question mark makes the :lang segment optional, so the route matches with or without it. A plain :lang requires a value, and a splat must be the last part of a pattern.
  3. 3. Where do you find the rest of the path matched by files/*?

    The splat value is stored under the key "", so you read it with params[""] or destructure it with a rename, such as const { "*": path } = useParams().
  4. 4. A user opens /products/abc and /products/99999 (no such product). What is the best handling?

    Check the shape first, then check that the record exists. They are different problems, and keeping them apart makes errors easier to understand and log.
  5. 5. Why encode a tag with encodeURIComponent before putting it in a link path?

    Characters like / ? and # have special meaning in URLs. Encoding keeps the value inside a single segment, and the router decodes it again when reading params.

Summary

  • A :name segment matches one whole URL segment, and useParams() returns its value under that name; values are always strings.
  • :name? makes a segment optional; * matches the rest of the path and is read as params["*"].
  • The router decodes values for you; you must encode pieces when you build URLs (encodeURIComponent or generatePath).
  • TypeScript describes the shape (string | undefined); it does not prove the value is valid.
  • Validate in two steps, shape first and existence second, and answer with a 400-style or a 404-style message.
  • Treat params as untrusted input, especially before they touch files, queries or HTML.

Next: Search Params and useSearchParams