Dynamic routing allows you to define routes at runtime (e.g., based on API data, user roles, or app state) instead of hardcoding them.
Key Concepts
Route Parameters (:id) → Match dynamic URL segments.
Nested Routes → Load components conditionally.
Data Fetching → Fetch data before rendering (e.g., loader in React Router 6.4+).
Example: Dynamic User Profiles
1. Define Dynamic Routes
// App.jsx
import { Routes, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<Routes>
{/* Static route */}
<Route path="/" element={<Home />} />
{/* Dynamic route */}
<Route path="/users/:userId" element={<UserProfile />} />
</Routes>
);
}
2. Access Route Parameters
// UserProfile.jsx
import { useParams } from 'react-router-dom';
export default function UserProfile() {
const { userId } = useParams(); // Extracts :userId from URL
return <h1>Profile Page for User: {userId}</h1>;
}