Client-Side Routing
React Router is the standard library for navigation in React apps. It enables client-side routing — switching between views without full page reloads. This makes your app feel fast and responsive like a native application.
React Router v6 uses the Routes and Route components to define your app's URL structure, and Link/NavLink for navigation.
Example
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/users">Users</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/users" element={<UserList />} />
<Route path="/users/:id" element={<UserDetail />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
function UserDetail() {
const { id } = useParams();
return <h1>User #{id}</h1>;
}
function NotFound() {
return <h1>404 - Page Not Found</h1>;
} - BrowserRouter — Wraps your app and enables routing
- Routes — Renders the first matching Route
- Route — Maps a URL path to a component
- Link — Navigates without page reload (replaces tags)
- useParams() — Access URL parameters like :id
- useNavigate() — Programmatic navigation
- path="*" — Catch-all route for 404 pages
Notes
- Install React Router with: npm install react-router-dom. Always use Link instead of tags for internal navigation to prevent full page reloads.
