React Router DOM
Overview
By default, React builds Single Page Applications (SPAs). This means there is only one physical HTML file (index.html) delivered from the server. If a user clicks a link to go from the 'Home' page to the 'About' page, a traditional website would fetch a completely new about.html file from the server, causing a slow, jarring full-page refresh.
To create the illusion of multiple fast, seamless pages in an SPA, we use Client-Side Routing. The industry-standard library for this is React Router DOM.
React Router intercepts the user's click on a link, forcefully stops the browser from making a network request to the server, and instantly swaps out the React components currently on the screen. It simultaneously updates the browser's URL bar and history stack (allowing the Back button to work perfectly), making the user feel like they navigated to a new page, even though they technically never left index.html.
Syntax
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
// 1. BrowserRouter wraps the entire app, enabling the routing engine
<BrowserRouter>
<nav>
{/* 2. Link replaces the standard HTML <a> tag to prevent full-page refreshes */}
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
{/* 3. Routes is the container where components will be swapped in and out */}
<Routes>
{/* 4. Route defines a specific URL path and the Component to render */}
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="*" element={<NotFoundPage />} /> {/* Catch-all 404 */}
</Routes>
</BrowserRouter>
);
}Common Pitfalls
- Using standard <a> tags: If you write
<a href="/about">About</a>, the browser will do a hard refresh, wipe out your entire React state (including global context/Redux), and reload the application from scratch. You MUST use React Router's<Link to="/about">component to ensure seamless, state-preserving client-side navigation.
Interview Questions
In Server-Side Routing, every URL navigation requests a brand new, fully rendered HTML document from the server, causing a page flash. In Client-Side Routing (React Router), the server only ever sends one initial HTML file. When the URL changes, Javascript takes over, prevents the network request, and instantly swaps which UI components are visible on the screen.
You use the useNavigate hook provided by React Router. E.g., const navigate = useNavigate(); followed by navigate('/dashboard'); inside the form submission handler.
Real-World Example
Programmatic Navigation and Active Links: NavLink is heavily used in Sidebars and Headers to automatically highlight the current page the user is on. useNavigate is essential for redirecting users after asynchronous operations like saving settings or logging out.
import { NavLink, useNavigate } from 'react-router-dom';
function AuthNavigation() {
const navigate = useNavigate();
const handleLogout = async () => {
await api.logout();
// Programmatically push the user back to the login screen
// The 'replace: true' option prevents them from using the Back button to return here
navigate('/login', { replace: true });
};
return (
<nav>
{/* NavLink is a special version of Link that automatically knows if it is 'active' */}
<NavLink
to="/dashboard"
className={({ isActive }) => isActive ? 'text-blue-500 font-bold' : 'text-gray-500'}
>
Dashboard
</NavLink>
<button onClick={handleLogout}>Log Out</button>
</nav>
);
}Check Your Knowledge
Test your understanding of React Router DOM with these quick questions.