Why a Router?
React itself has no concept of URLs or navigation. React Router is the most widely used library for mapping URL paths to components, enabling multi-page-feeling apps that never actually reload the page.
Installing React Router
npm install react-router-domBasic Route Setup
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}Dynamic Route Parameters
A route path can include a parameter (prefixed with :), and useParams() reads its current value inside the matched component.
Dynamic Route with useParams
import { useParams } from "react-router-dom";
<Route path="/users/:userId" element={<UserProfile />} />;
function UserProfile() {
const { userId } = useParams();
return <h1>Viewing user {userId}</h1>;
}Frameworks Often Handle Routing Differently
Full-stack React frameworks like Next.js use file-based routing instead of declaring <Route> components manually — the folder structure under an app or pages directory determines the URL structure automatically.
Best Practice
Keep route definitions in one central place (or a small number of route files) rather than scattering <Route> elements throughout the codebase — it keeps the app’s overall URL structure easy to see at a glance.