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 withuseParams()orparamsin loaders and actions. - Optional segment:
path: ":lang?/about"matches/aboutand/en/about. - Splat (catch-all):
path: "files/*", read withparams["*"]. - 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";23type Product = { id: string; name: string };45function ProductPage() {6 const { productId } = useParams(); // "42" for /products/427 const product = useLoaderData() as Product;8 return <h1>#{productId}: {product.name}</h1>;9}1011function FileViewer() {12 const params = useParams();13 return <p>Viewing {params["*"]}</p>; // "docs/2026/report.pdf" for /files/docs/2026/report.pdf14}1516export 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 segment28 { path: "/files/*", Component: FileViewer }, // splat29]);
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.