Routing with React Router
By the end of this lesson KharchaBook will have real addresses: /expenses for the list, /expenses/20 for one expense and a friendly "Page not found" for anything else. You will add React Router, share one header between pages with a layout route, read the id from the URL, tell an API 404 from a page 404, and see why a refresh on /expenses/20 needs help from the server.
What you should know first: Fetching Data from Your API, whose useApi hook every page here reuses. React Router itself is taught step by step in Routing with React Router in the React course. This lesson spends its time on how routes and the API fit together. Versions used: react-router 8.5.1, checked on npm on 16 November 2026, with React 19.3.1 and Vite 8.3.8. Every result below was seen in a real Chrome session against the API from the earlier lessons.
Why the URL matters
Think of a postal address in Pune: "Flat 4, Kothrud, 411038". Anyone can write it down, share it on WhatsApp and reach the same door later. A screen with its own URL works the same way. Priya can bookmark her expense list, send Rohan a link to one bill, and press the browser's Back button to return.
Right now KharchaBook has one screen and one address. Client-side routing fixes that. The browser address changes, and React swaps the screen without asking the server for a new HTML page. Only the data travels, as JSON from the API.
There are now two kinds of path in the app, and keeping them apart avoids confusion:
| Path | Who answers | What comes back |
|---|---|---|
/expenses/20 | React Router, in the browser | A screen |
/api/expenses/20 | Express, on the server | JSON |
A page path describes what the user sees. An API path describes which data the page needs. They often look alike, but they are different contracts.
Step 1: install React Router
From the kharchabook folder:
npm install react-router -w clientadded 3 packages, changed 1 package, and audited 167 packages in 31s 52 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
Version 8 is a single package, react-router. Older tutorials install react-router-dom; that package no longer exists in version 8. React Router 8.5.1 asks for React 19.2.7 or newer and Node.js 22.22 or newer in its package.json, so our React 19.3 and Node.js 26 are fine. (npm printed an EBADENGINE warning on our older test machine; on Node.js 26 it does not.)
Step 2: wrap the app in a router
BrowserRouter watches the address bar and tells the components below it which URL is showing. It goes in src/main.jsx, around <App />:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import "./index.css";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
);React Router also has a "data mode" with createBrowserRouter and loaders, shown in the React course. We stay with the simpler declarative mode, because KharchaBook already loads data with useApi.
Step 3: the route table
src/App.jsx becomes a map from URL patterns to pages:
import { Navigate, Route, Routes } from "react-router";
import Layout from "./components/Layout.jsx";
import ExpensesPage from "./pages/ExpensesPage.jsx";
import ExpenseDetailPage from "./pages/ExpenseDetailPage.jsx";
import NotFoundPage from "./pages/NotFoundPage.jsx";
export default function App() {
return (
<Routes>
<Route element={<Layout />}>
<Route index element={<Navigate to="/expenses" replace />} />
<Route path="expenses" element={<ExpensesPage />} />
<Route path="expenses/:id" element={<ExpenseDetailPage />} />
<Route path="*" element={<NotFoundPage />} />
</Route>
</Routes>
);
}Read it line by line:
- The outer
<Route element={<Layout />}>has nopath. It is a layout route: it wraps all the pages inside it with the same header. indexmeans "exactly the parent's path", here/.<Navigate to="/expenses" replace />sends the visitor on to the list.replaceswaps the history entry, so Back does not bounce them to/again.:idis a dynamic segment. It matches any one piece of the path, such as20, and hands it to the page.*matches everything the other routes did not. It must exist, or a typo shows a blank screen.
React Router ranks routes by how specific they are, not by their order in the file. When the forms lesson adds expenses/new, it will beat expenses/:id for the path /expenses/new wherever you put it.
Step 4: one layout for every page
src/components/Layout.jsx holds the header and a navigation link. <Outlet /> marks the spot where the matched page appears:
import { NavLink, Outlet } from "react-router";
export default function Layout() {
return (
<>
<header className="app-header">
<h1>KharchaBook</h1>
<nav aria-label="Main">
<NavLink to="/expenses" end>Expenses</NavLink>
</nav>
</header>
<main>
<Outlet />
</main>
</>
);
}NavLink is a Link that knows whether it points at the current page. When it does, it adds the class active and aria-current="page", so screen readers announce "current page". Two CSS rules in index.css make the active link bold. The end prop means "active only on /expenses itself, not on /expenses/20".
Use Link and NavLink for every move inside the app, never a plain <a href>. A plain link makes the browser download index.html again, restart React and throw away all state. Link changes the URL with the History API and lets React swap the page instantly.
Step 5: a detail page that reads the URL
src/pages/ExpenseDetailPage.jsx gets the id from the URL with useParams() and asks the API for that one expense:
import { Link, useParams } from "react-router";
import { useApi } from "../api/useApi.js";
import { formatDate, formatINR } from "../utils/format.js";
export default function ExpenseDetailPage() {
const { id } = useParams();
const expense = useApi(`/api/expenses/${encodeURIComponent(id)}`);
if (expense.error?.status === 404) {
return (
<section>
<h2>Expense not found</h2>
<p>{expense.error.message}</p>
<Link to="/expenses">Back to the list</Link>
</section>
);
}
if (expense.error) return <p role="alert">{expense.error.message}</p>;
if (!expense.data) return <p role="status">Loading expense...</p>;
const e = expense.data;
return (
<section>
<h2>{e.note || e.category}</h2>
<dl className="details">
<dt>Amount</dt><dd>{formatINR(e.amount)}</dd>
<dt>Category</dt><dd>{e.category}</dd>
<dt>Date</dt><dd>{formatDate(e.spentOn)}</dd>
</dl>
<Link to="/expenses">Back to the list</Link>
</section>
);
}Three details matter here.
Params are always strings, and always untrusted. Anyone can type /expenses/abc or something stranger. encodeURIComponent keeps odd characters from changing the API path, and the server already answers a bad id with a clean 404, as built in the Express lesson. The React page never decides who may see expense 20; the API's user_id filter from the auth lesson does.
The path drives the request. When the user moves from /expenses/20 to /expenses/19, React Router keeps the same component on screen and only id changes. Because the API path is built from id, useApi cancels the old request and starts a new one. A page that copied id into state once would show the old expense.
Two kinds of "not found". A path that matches no route shows NotFoundPage. A path that matches the route but names a missing expense shows the API's own 404 message. Both are friendly, and neither is a blank screen.
src/pages/NotFoundPage.jsx uses useLocation() to show the path the visitor asked for, with a Link back to /expenses. Finally, in ExpenseList.jsx, each note becomes a link: <Link className="note" to={/expenses/${e.id}}>{e.note || e.category}</Link>.
Step 6: try it in the browser
Start both halves with npm run dev, log in from the console as in the last lesson, and open http://localhost:5173/. Here is what our Chrome session showed (as before, our run used spare ports, so only port numbers were changed):
| You do | Address bar | Screen |
|---|---|---|
Open / | /expenses | "4 expenses, total ₹22,450.50" and the list |
| Click "Misal pav, family outing" | /expenses/20 | Heading "Misal pav, family outing", ₹650.00, Eating out, 8 Nov 2026 |
| Press Back | /expenses | The list again |
Type /expenses/999 | /expenses/999 | "Expense not found" and "Expense 999 was not found." |
Type /budgets | /budgets | "Page not found" and "There is no page at /budgets." |
The network log for the click showed only API calls, and no new page load:
REQ GET http://localhost:5173/api/expenses/20 REQ GET http://localhost:5173/api/expenses/20 FAILED net::ERR_ABORTED (canceled) RES 200 http://localhost:5173/api/expenses/20
The doubled, cancelled request is StrictMode in development, exactly as explained in the last lesson.
Deep links need the server's help
Typing /expenses/999 into the address bar is different from clicking a link. The browser asks the server for /expenses/999. In development, Vite answers any unknown page path with index.html, React starts, and the router reads the address. That is why the table above worked.
A plain static web server does not do this. It looks for a file called expenses/999, finds none and returns its own 404 page. So in production the server must follow one rule: API paths go to Express, files that exist are sent as files, and every other path gets index.html. The Deploying a PERN App lesson sets this up. Never let /api/... fall back to index.html: a mistyped API call would then get HTML with status 200, and response.json() would fail with a confusing error.
See route matching in action
This example builds a tiny route matcher with plain React, so you can watch how patterns turn paths into a page name and params. It is a teaching model of what React Router does, not a replacement for it.
import { useState } from "react";
import { createRoot } from "react-dom/client";
// The same kind of table as KharchaBook's App.jsx.
const routes = [
{ pattern: "/expenses", page: "ExpensesPage" },
{ pattern: "/expenses/new", page: "NewExpensePage" },
{ pattern: "/expenses/:id", page: "ExpenseDetailPage" },
{ pattern: "*", page: "NotFoundPage" },
];
// Compares a pattern with a path, piece by piece; ":name" captures a value.
function match(pattern, path) {
if (pattern === "*") return {};
const want = pattern.split("/");
const got = path.split("/");
if (want.length !== got.length) return null;
const params = {};
for (let i = 0; i < want.length; i++) {
if (want[i].startsWith(":")) params[want[i].slice(1)] = decodeURIComponent(got[i]);
else if (want[i] !== got[i]) return null;
}
return params;
}
function resolve(path) {
for (const route of routes) {
const params = match(route.pattern, path);
if (params) return { page: route.page, params };
}
}
const paths = ["/expenses", "/expenses/new", "/expenses/20", "/expenses/20/edit", "/budgets"];
function App() {
const [path, setPath] = useState("/expenses");
const { page, params } = resolve(path);
function go(next) {
const found = resolve(next);
console.log(next, "->", found.page, JSON.stringify(found.params));
setPath(next);
}
return (
<>
{paths.map((p) => (
<button key={p} onClick={() => go(p)} style={{ marginRight: 6 }}>{p}</button>
))}
<p>Address: <code>{path}</code></p>
<p>Page: <strong>{page}</strong>, params: <code>{JSON.stringify(params)}</code></p>
</>
);
}
createRoot(document.getElementById("root")).render(<App />);Click each button from left to right. The console shows:
/expenses -> ExpensesPage {}
/expenses/new -> NewExpensePage {}
/expenses/20 -> ExpenseDetailPage {"id":"20"}
/expenses/20/edit -> NotFoundPage {}
/budgets -> NotFoundPage {}Notice that "20" is a string, just like useParams() gives you. This simple matcher needs /expenses/new listed before /expenses/:id, or "new" would be taken as an id. React Router ranks routes for you, so it gets this right in any order.
Common mistakes
- Plain
<a href>for links inside the app. The whole app reloads and loses its state. UseLinkorNavLink. - Copying a URL param into state once. Moving from one id to another then shows stale data. Build the API path from the param on every render.
- Trusting the param. It is user input. Encode it in the API path and let the server check ownership.
- No
*route. A mistyped address shows an empty page instead of a helpful message. - Forgetting the production fallback. Refreshing
/expenses/20gives the web server's 404 until every non-API path servesindex.html. - Mixing versions.
Switch,useHistoryandreact-router-dombelong to older versions; version 8 usesRoutes,useNavigateandreact-router.
Interview questions
1. What is client-side routing, and how is it different from server-side routing?
With server-side routing, every URL change downloads a new HTML page from the server. With client-side routing, one HTML page loads once, and a router in the browser changes the URL with the History API and swaps components. Only data is fetched afterwards, so moving between screens is fast and state can survive.
2. Why does refreshing a deep link sometimes return 404 in production?
The browser asks the server for that path directly. If the server only serves real files, it has no file for /expenses/20. The fix is a fallback that serves index.html for every path that is not an API route or an existing file, so the client router can take over.
3. What is a layout route?
A route that renders shared UI, such as a header and navigation, and an <Outlet /> where the matched child route appears. It often has no path of its own. It avoids repeating the header in every page.
4. A page reads id from useParams(). How do you keep it safe?
Treat it as untrusted text. Encode it when building the API path, show friendly states for loading and 404, and rely on the server to validate the id and check that the record belongs to the logged-in user. The client must never be the only check.
Key points
- Install
react-router(version 8) and wrap<App />inBrowserRouter. RoutesandRoutemap paths to pages; a layout route with<Outlet />shares the header.- Use
LinkandNavLinkfor in-app moves;NavLinkmarks the current page witharia-current. useParams()returns strings; build the API path from them so data follows the URL.- Keep page paths (
/expenses/20) and API paths (/api/expenses/20) separate, and handle both kinds of 404. - Production servers must send
index.htmlfor unknown page paths, but never for/apipaths.
Exercise
Add a categories screen. Create src/pages/CategoriesPage.jsx at the path /categories. It should load GET /api/categories with useApi and show each category name in a list. Add a NavLink to it in Layout.jsx. Check that /categories is bold in the navigation when you are on it, and that /categories/whatever shows the "Page not found" screen.
Show solution
// src/pages/CategoriesPage.jsx
import { useApi } from "../api/useApi.js";
export default function CategoriesPage() {
const categories = useApi("/api/categories");
if (categories.error) return <p role="alert">{categories.error.message}</p>;
if (!categories.data) return <p role="status">Loading categories...</p>;
return (
<section>
<h2>Categories</h2>
<ul>
{categories.data.map((c) => (
<li key={c.id}>{c.name}</li>
))}
</ul>
</section>
);
}In App.jsx, add <Route path="categories" element={<CategoriesPage />} /> inside the layout route, and in Layout.jsx add <NavLink to="/categories">Categories</NavLink>. The page lists the eight categories from Groceries to Other. /categories/whatever matches no route, so the * route shows "There is no page at /categories/whatever."
Quick Quiz
1. Which link keeps React running and only swaps the page?
Link changes the URL with the History API; the other two make the browser load a new page.
2. On /expenses/20, what does useParams() return?
URL params are always strings; convert them yourself if you need a number.
3. A user refreshes /expenses/20 on a production server and sees the server's own 404 page. What is missing?
The browser asked the server for the path directly, before React could run.
4. Why must /api/... paths never fall back to index.html?
The client expects JSON errors from the API; HTML makes response.json() fail confusingly.
Learn PERN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
