Introduction
Real applications rarely have a fixed, finite set of pages. A product catalog needs a route per product, a blog needs a route per post, and a user profile page needs a route per user ID. Dynamic routing lets a single Route definition handle an entire family of URLs by declaring path segments as parameters, such as '/products/:productId'. React Router then extracts the matched segment so the component can fetch or display the right data.
Cricket analogy: Instead of writing a separate page for every player, a single route like '/players/:playerId' lets one template display Kohli, Root, or Babar depending on which segment the URL matches, with React Router extracting the id.
Syntax
import { Routes, Route, useParams, useNavigate } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/products" element={<ProductList />} />
<Route path="/products/:productId" element={<ProductDetail />} />
</Routes>
);
}
function ProductDetail() {
const { productId } = useParams();
const navigate = useNavigate();
return (
<div>
<h2>Product #{productId}</h2>
<button onClick={() => navigate(-1)}>Go Back</button>
</div>
);
}Explanation
A colon-prefixed segment in a path, like ':productId', tells React Router to treat that part of the URL as a dynamic parameter rather than a literal string. The useParams hook reads the current URL and returns an object whose keys match the parameter names defined in the route, so '/products/42' yields { productId: '42' }. All URL parameters are returned as strings, so numeric values often need explicit conversion. The useNavigate hook returns a function for programmatic navigation, useful for redirecting after form submissions, login, or button clicks; calling navigate(-1) mimics the browser's back button, while navigate('/path') pushes a new entry onto the history stack.
Cricket analogy: A route segment like ':matchId' tells React Router to treat it as dynamic, and useParams turns '/matches/42' into { matchId: '42' }, a string needing conversion; useNavigate can then push to '/scorecard' after a toss decision or call navigate(-1) to return to the fixtures list.
Example
function ProductList() {
const products = [{ id: 1, name: 'Keyboard' }, { id: 2, name: 'Mouse' }];
const navigate = useNavigate();
return (
<ul>
{products.map((p) => (
<li key={p.id} onClick={() => navigate(`/products/${p.id}`)}>
{p.name}
</li>
))}
</ul>
);
}
function ProductDetail() {
const { productId } = useParams();
const product = products.find((p) => p.id === Number(productId));
return <h2>{product ? product.name : 'Product not found'}</h2>;
}Output
Clicking 'Keyboard' in the list programmatically navigates the browser to '/products/1' and renders ProductDetail, which reads productId ('1') from useParams, converts it to a number, and looks up the matching product to display 'Keyboard'. If the URL contained an id with no matching product, the component gracefully renders 'Product not found' instead of crashing.
Cricket analogy: Clicking 'Root' in a player list navigates to '/players/1', and PlayerDetail reads playerId ('1') from useParams, converts it to a number, and looks up Joe Root; an unmatched id gracefully renders 'Player not found' instead of crashing.
Key Takeaways
- Prefix a path segment with a colon (e.g. :id) to declare it as a dynamic URL parameter.
- useParams() returns an object of the matched parameters, always as strings.
- useNavigate() enables programmatic navigation, including redirects and going back with navigate(-1).
- Convert string params (e.g. with Number()) before using them for numeric comparisons or lookups.
- Dynamic routes let one Route definition serve unlimited data-driven pages.
Practice what you learned
1. How do you declare a dynamic segment in a React Router path?
2. What type are the values returned by useParams()?
3. What does navigate(-1) do when called from useNavigate()?
4. For the route path="/users/:userId", what would useParams() return for the URL '/users/7'?
Was this page helpful?
You May Also Like
React Router Basics
Learn how to add client-side routing to a React app using React Router v6's Routes, Route, Link, and NavLink components.
Nested Routes and Layouts
Build shared layouts and nested UI in React Router v6 using nested Route definitions and the Outlet component.
The useEffect Hook
Understand useEffect for side effects in function components, covering the dependency array, cleanup functions, and effect timing.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics