Dynamic Routes
Dynamic Routes cover parameterized paths, useParams, resource loading with cancellation, invalid vs missing resources, and safe URL design.
Course: React — Routing & API Integration Lesson: 05
Learning objectives
Define parameterized route paths, read route parameters with useParams, validate identifiers, and handle missing resources safely.
What is a dynamic route?
A dynamic route contains a path segment whose value varies by resource. For example, a SaaS order application may have /orders/1001, /orders/1002, and /orders/1003. Instead of declaring a route for every order, define one pattern:
<Route path="/orders/:orderId" element={<OrderDetailsPage />} />
The :orderId segment is a parameter.
Read parameters with useParams
import { useParams } from "react-router-dom";function OrderDetailsPage() {const { orderId } = useParams();return <h1>Order: {orderId}</h1>;}
Route parameters are strings. If the backend expects a numeric identifier, validate and convert it deliberately rather than assuming it is a valid number.
Load the resource
function OrderDetailsPage() {const { orderId } = useParams();const [order, setOrder] = useState(null);const [status, setStatus] = useState("loading");const [error, setError] = useState(null);useEffect(() => {const controller = new AbortController();async function loadOrder() {setStatus("loading");setError(null);try {const response = await fetch(`/api/orders/${encodeURIComponent(orderId)}`, {signal: controller.signal});if (!response.ok) throw new Error("Unable to load order");const result = await response.json();setOrder(result);setStatus("success");} catch (err) {if (err.name !== "AbortError") {setError(err);setStatus("error");}}}loadOrder();return () => controller.abort();}, [orderId]);if (status === "loading") return <p>Loading order…</p>;if (status === "error") return <p>{error.message}</p>;if (!order) return <p>Order not found.</p>;return <h1>{order.orderNumber}</h1>;}
This example demonstrates parameter-driven fetching and request cancellation. In a larger application, a dedicated data-fetching layer may provide caching, retries, and request deduplication.
Resource not found vs invalid input
A malformed identifier and a valid identifier for a nonexistent order are different cases. Validate the identifier format at the UI boundary where useful, but let the backend remain authoritative about whether a resource exists and whether the current user can access it.
URL design
Prefer stable, readable resource paths such as /customers/:customerId/orders/:orderId. Avoid placing secrets, access tokens, or sensitive personal data in path segments or query strings because URLs may be recorded in logs, browser history, and analytics.
Common mistakes
- Forgetting that
useParams()values are strings. - Failing to refetch when the parameter changes.
- Not cancelling or ignoring stale requests.
- Treating an identifier as proof of authorization.
- Showing a generic blank screen when a resource is missing.
Best practices
- Use descriptive parameter names.
- Encode values when constructing URLs.
- Handle loading, error, empty, and success states.
- Cancel obsolete requests where appropriate.
- Enforce resource-level authorization on the server.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1How do you define a dynamic route?
BeginnerModel answer
Declare a parameterized segment such as<Route path="/orders/:orderId" element={...} />so one page serves many resource URLs.2How do you avoid stale data when route parameters change?
BeginnerModel answer
Refetch when the parameter changes, and cancel or ignore obsolete responses withAbortControlleror equivalent cleanup.
Intermediate
3What does useParams return?
IntermediateModel answer
An object of matched path parameters as strings—for example{ orderId: "1001" }—which you validate and convert as needed.4What should the UI do when a resource does not exist?
IntermediateModel answer
Show a clear not-found state distinct from loading and generic errors, and offer a safe path back into the application.
Advanced
5Why can a route parameter not be trusted as authorization?
AdvancedModel answer
Anyone can type or forge a URL.
The backend must verify the caller may access that resource regardless of what appears in the path.
Practice
Create /customers/:customerId, fetch customer details, and test valid, invalid, and nonexistent identifiers.