React Dynamic Routes
Dynamic routing is the cornerstone of scalable React applications. Instead of hardcoding every possible URL (like /user/1, /user/2, etc.), you define a single route template.
The Dynamic Segment
In React Router v6, you create a dynamic segment in a path by prefixing a word with a colon (:). For instance, <Route path="/profile/:userId" /> tells the router that userId is a variable. When a user navigates to /profile/42, the router matches this route and stores the value "42" under the key userId.
Extracting with useParams
Once matched, the component rendered by that route needs access to the dynamic data. This is where the useParams hook comes in. It returns an object containing all dynamic segments mapped to their URL values.
import { useParams } from 'react-router-dom';
function Profile() {
const { userId } = useParams();
return <div>User ID: {userId}</div>;
}Linking to Dynamic Routes
When linking to a dynamic route, you don't use the colon syntax. The colon is only for defining the route pattern. To link, you provide the actual value, usually by injecting a variable into a string using template literals: <Link to={'/profile/' + user.id}>.
View Routing Patterns+
Multiple Parameters: path="/blog/:year/:month/:slug"
Optional Parameters: In React Router v6, optional params aren't natively supported via regex like v5. You usually define multiple routes or use trailing splats *.
Query Parameters: Data after the ? (e.g., ?sort=asc) is NOT handled by useParams. For that, you use the useSearchParams hook.
