ReactEasy

What is dynamic routing?

Dynamic routing means routes contain variable segments, like /users/:userId or /blog/:slug, so one route definition matches many URLs. The router extracts the values (userId: "42") and the component or loader uses them to fetch and render the right data.

In React Router

  • Dynamic segment: path: "users/:userId", read with useParams() or params in loaders and actions.
  • Optional segment: path: ":lang?/about" matches /about and /en/about.
  • Splat (catch-all): path: "files/*", read with params["*"].
  • Multiple segments: projects/:projectId/tasks/:taskId.

In Next.js

Folder names in brackets: app/blog/[slug]/page.tsx, [...slug] for catch-all, [[...slug]] for optional catch-all.

"Dynamic routing" can also mean

  • Routes defined at runtime from data (for example from a CMS or permissions), by building the route config array dynamically.
  • React Router's philosophy that routes are part of rendering (in declarative mode).

Good practices

  • Validate params: they are strings from the URL and may be malformed.
  • Return a 404 or render a not-found UI for unknown IDs.
  • Use loaders to fetch data based on params before rendering, avoiding loading spinners on every navigation.
  • Encode values when building links: `/search/${encodeURIComponent(term)}`.

Code example

tsx
1import { createBrowserRouter, data, useLoaderData, useParams } from "react-router";
2
3type Product = { id: string; name: string };
4
5function ProductPage() {
6 const { productId } = useParams(); // "42" for /products/42
7 const product = useLoaderData() as Product;
8 return <h1>#{productId}: {product.name}</h1>;
9}
10
11function FileViewer() {
12 const params = useParams();
13 return <p>Viewing {params["*"]}</p>; // "docs/2026/report.pdf" for /files/docs/2026/report.pdf
14}
15
16export const router = createBrowserRouter([
17 {
18 path: "/products/:productId",
19 loader: async ({ params }) => {
20 if (!/^\d+$/.test(params.productId!)) throw data("Invalid id", { status: 400 });
21 const res = await fetch(`/api/products/${params.productId}`);
22 if (res.status === 404) throw data("Not found", { status: 404 });
23 return res.json();
24 },
25 Component: ProductPage,
26 },
27 { path: "/:lang?/about", Component: () => <h1>About</h1> }, // optional segment
28 { path: "/files/*", Component: FileViewer }, // splat
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.

Open in study app