Routing (Common in Real Apps) 🧭
Routing lets single-page apps feel like multi-page experiences. React Router v7 bridges React 18 → 19 with data-aware routing plus framework-style features.
1) Client-side Routing Basics ⚛️
import { createBrowserRouter, RouterProvider, Link } from "react-router-dom";
const router = createBrowserRouter([
{ path: "/", element: <Home /> },
{ path: "/about", element: <About /> }
]);
function App() {
return (
<RouterProvider router={router} />
);
}
function Nav() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}RouterProvidersyncs URL to UI without page reloads.Linkprevents full refreshes and preserves application state.
2) Nested Routes & Layouts 🧱
- Define parent routes that render
<Outlet />for children. - Build shared layouts (nav, sidebars) once; nested routes fill in the content area.
const router = createBrowserRouter([
{
path: "/dashboard",
element: <DashboardLayout />, // contains Outlet
children: [
{ path: "analytics", element: <Analytics /> },
{ path: "settings", element: <Settings /> }
]
}
]);function DashboardLayout() {
return (
<section>
<Sidebar />
<main>
<Outlet />
</main>
</section>
);
}3) Data Router Patterns 🧠
React Router v7 introduces loaders, actions, and error boundaries so data + UI stay aligned.
const router = createBrowserRouter([
{
path: "/projects",
element: <ProjectsPage />,
loader: async ({ request }) => {
const res = await fetch("/api/projects", { signal: request.signal });
return res.json();
},
action: async ({ request }) => {
const formData = await request.formData();
await fetch("/api/projects", {
method: "POST",
body: formData
});
return null;
},
errorElement: <ErrorBoundary />
}
]);- Loader: fetch data before rendering; uses
request.signalfor cancellation. - Action: handle mutations triggered by forms or submissions.
- Error boundaries render friendly fallbacks when loaders or actions fail.
🧠 Think of React Router v7 as a mini framework: it orchestrates navigation, data fetching, and error handling coherently.
Key Takeaways ✅
- Client-side routing maps URLs to components without page reloads.
- Nested routes and layouts keep shared UI DRY while children swap content.
- Data routers (v7) prefetch data, manage mutations, and propagate errors gracefully.
Recap 🔄
React Router v7 makes SPAs feel structured: define routes, layer layouts with <Outlet />, and leverage loaders/actions for data-driven pages. Treat it as the routing backbone bridging modern React features into framework-like ergonomics.
Last updated on