Dynamic Routes
Dynamic routes in React 19 enable you to create client-side routing applications with ease. This feature allows you to render different components based on the URL. With dynamic routes, you can build complex, data-driven applications that respond to user interactions.
Basic Example
To get started with dynamic routes, you’ll need to use a library like React Router. Here’s a simple example:
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:id" element={<User />} />
</Routes>
</BrowserRouter>
);
}
function Home() {
return <h1>Welcome to the home page</h1>;
}
function User() {
const { id } = useParams();
return <h1>User {id}</h1>;
}In this example, we’re using the React Router library to create two routes: one for the home page and one for a user page with a dynamic ID.
Advanced Usage
Let’s say you want to fetch data from an API based on the dynamic route. You can use the useParams hook to get the route parameters and then fetch the data:
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
const [user, setUser] = useState({});
useEffect(() => {
fetch(`https://api.example.com/users/${id}`)
.then(response => response.json())
.then(data => setUser(data));
}, [id]);
return <h1>User {user.name}</h1>;
}In this example, we’re using the useParams hook to get the user ID and then fetching the user data from an API using the useEffect hook.
Best Practices
When working with dynamic routes, keep the following best practices in mind:
- Use meaningful route names to make your code easier to understand
- Use route parameters to pass data between components
- Use the
useParamshook to access route parameters - Use the
useEffecthook to fetch data based on route changes
Key Takeaways
Here are the key takeaways from this article:
- Dynamic routes enable you to create client-side routing applications with ease
- Use React Router to create dynamic routes
- Use the
useParamshook to access route parameters - Use the
useEffecthook to fetch data based on route changes