Dynamic Routing in React

📘 React.js 👁 45 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Dynamic routing allows you to create routes that change based on URL parameters, such as user IDs, product IDs, or slugs. It is commonly used with React Router.


Why Dynamic Routing?

  • Display content based on URL data

  • Build user profiles, product pages, blogs

  • Avoid creating separate routes for each item

Example URL:

/users/101 /products/iphone

Defining a Dynamic Route

Use a parameter in the route path with :.

import { Route, Routes } from "react-router-dom"; <Routes> <Route path="/user/:id" element={<User />} /> </Routes>

Accessing Route Parameters (useParams)

import { useParams } from "react-router-dom"; function User() { const { id } = useParams(); return <h2>User ID: {id}</h2>; }

Multiple Route Parameters

<Route path="/product/:category/:id" element={<Product />} />
function Product() { const { category, id } = useParams(); return <p>{category} - {id}</p>; }

Dynamic Routing with Data Fetching

function UserProfile() { const { id } = useParams(); const [user, setUser] = React.useState(null); React.useEffect(() => { fetch(`/api/users/${id}`) .then(res => res.json()) .then(data => setUser(data)); }, [id]); return user ? <h2>{user.name}</h2> : <p>Loading...</p>; }

Optional Parameters (Workaround)

React Router does not support optional params directly, but you can:

  • Use multiple routes

  • Use query parameters

Example:

/products?id=10

Using useNavigate with Dynamic Routes

navigate(`/user/${userId}`);

Dynamic Links

<Link to={`/product/${product.id}`}> View Product </Link>

Nested Dynamic Routes

<Route path="/users/:id" element={<User />}> <Route path="posts" element={<Posts />} /> </Route>

Common Use Cases

  • User profile pages

  • Product details

  • Blog posts

  • Dashboards


Best Practices

  • Use meaningful parameter names

  • Handle loading and error states

  • Validate route parameters

  • Keep routes organized


Key Points

  • Dynamic routes use URL parameters

  • useParams reads route values

  • Routes update without page reload

  • Ideal for data-driven pages


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes