Declarative routing for React web applications
react-router-dom is the standard routing solution for React single-page applications, built on top of the core react-router package. It leverages the HTML5 History API to manage navigation between views without full page reloads, maintaining a fluid user experience while updating the URL and browser history. With over 20 million weekly downloads, it's the de facto routing library for client-side React web applications.
The library provides declarative route definitions using JSX components like
Designed for intermediate to advanced React developers building complex SPAs, react-router-dom supports dynamic route parameters, nested route structures with outlets, programmatic navigation via hooks, and protected routes through redirects. The package abstracts away the complexity of manual history management while providing low-level access when needed through hooks like useNavigate, useParams, and useLocation. It's particularly valuable for applications with multiple views, authentication flows, dashboard layouts, or any scenario requiring URL-driven state management.
import { createBrowserRouter, RouterProvider, Route, Link, useParams, useLoaderData, Navigate, Outlet } from 'react-router-dom';
const fetchUser = async (userId) => {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!res.ok) throw new Response('User not found', { status: 404 });
return res.json();
};
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> | <Link to="/users/1">User 1</Link> | <Link to="/users/2">User 2</Link>
</nav>
<main>
<Outlet />
</main>
</div>
);
}
function Home() {
return <h1>Welcome to React Router</h1>;
}
function UserProfile() {
const user = useLoaderData();
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Company: {user.company.name}</p>
</div>
);
}
function ProtectedRoute({ children }) {
const isAuthenticated = localStorage.getItem('token');
return isAuthenticated ? children : <Navigate to="/" replace />;
}
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{ index: true, element: <Home /> },
{
path: 'users/:userId',
element: <ProtectedRoute><UserProfile /></ProtectedRoute>,
loader: ({ params }) => fetchUser(params.userId),
errorElement: <div>Error loading user</div>
}
]
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;Multi-page dashboard applications: Build admin panels or SaaS interfaces with nested navigation structures, where a main layout wraps sub-routes like /dashboard/users, /dashboard/analytics, and /dashboard/settings, all sharing a common sidebar and header through React Router's Outlet component.
Authentication-protected routes: Implement route guards that redirect unauthenticated users to a login page using loader functions or Navigate components, checking token validity before rendering protected resources without duplicating authentication logic across components.
Dynamic content pages: Create blog or e-commerce sites where routes like /posts/:slug or /products/:id extract URL parameters via useParams to fetch and display specific content, enabling shareable URLs and proper browser history navigation.
Form-heavy applications: Leverage action functions to handle form submissions server-style with request.formData(), managing validation, error states, and redirects after success while supporting progressive enhancement for JavaScript-disabled browsers.
Progressive web apps with offline support: Combine react-router-dom with service workers to create PWAs where client-side routing maintains navigation functionality when offline, with routes pre-loaded during the service worker installation phase.
npm install react-router-dompnpm add react-router-dombun add react-router-dom