Lesson 31 of 37React at scale
Client-Side Routing
How SPA routers work on the History API, React Router v7's modes and loaders, type-safe TanStack Router, code splitting, protected routes, and accessible navigation.
A product manager files two bugs on the same day. "When I refresh /projects/42 on staging I get a 404." And "After I click a link, the screen reader says nothing and the page is scrolled halfway down." Both are routing bugs, and neither lives in your components. A single-page app (SPA) swaps screens without asking the server for a new HTML page, so everything the browser used to do for free on navigation, such as updating the URL, restoring scroll, moving focus and handling 404s, becomes your router's job and your job. This lesson explains how routers work underneath, how the two routers you are most likely to meet (React Router and TanStack Router) are used at work, and the details that separate a smooth app from a broken one.
What a router actually does
Without a router, every link is a full page load: the browser throws away your JavaScript, your React state and your cache, and downloads a new document. A client-side router keeps the page alive and does four jobs instead:
- Intercept clicks on internal links and call
event.preventDefault(). - Change the URL without a reload, with
history.pushState(state, "", "/projects/42"). - Listen for the back and forward buttons, which fire a
popstateevent. - Match the current URL against a route table and render the right components.
There is one subtlety interviewers like. popstate fires only when the user (or code) traverses history: back, forward, history.go(). It does not fire when you call pushState or replaceState yourself. So a router must update its own state when it pushes, and listen to popstate for everything else. Browsers also have a newer Navigation API with a single navigate event covering every kind of navigation. Support has spread across engines, so check current support before relying on it directly; routers are where you will meet it first.
The demo below is a working router in about 70 lines. It uses an in-memory history (an array and an index) instead of window.history, so it cannot change this page's real URL, but the mechanics are the same: a store holding the location, useSyncExternalStore to subscribe, a Link that intercepts clicks, nested layout rendering through an Outlet, params, a 404, and focus moved to the new page's heading. Click around, then use the Back and Forward buttons.
Notice three things. Going back and then clicking a new link drops the forward entries, exactly like a browser. The layout never unmounts while you navigate inside it, so its state survives, which is the whole point of nested routes. And the active link gets aria-current="page", which is what NavLink in React Router adds for you.
Matching: patterns, params and ranking
Routes are patterns: /projects/:projectId has a dynamic segment that becomes a param, and * is a splat (catch-all) for 404s. Modern routers do not take the first pattern that fits. They rank all matching patterns and pick the most specific: static segments beat dynamic ones, and dynamic ones beat splats. That is why /projects/new works next to /projects/:projectId no matter the order you declare them. This matcher uses a simple scoring scheme to show the idea:
Press Run (⌘ Enter) to see what happens.Params are always strings, and they are user input. /projects/abc and /projects/-1 will reach your code, so validate params before you use them in a request.
Using the matcher and routes above, which pattern wins for this path?
console.log(resolve("/projects/new/settings").pattern);React Router v7: three modes
React Router is the most widely used React router. Version 7 merged in Remix, and you now choose how much of it to use. Imports come from the react-router package (the old react-router-dom package still exists and re-exports it, so you will see both in codebases).
- Declarative mode:
<BrowserRouter>,<Routes>and<Route>elements. URL matching, links and params, and nothing else. Data loading is up to you, usually in components with TanStack Query. - Data mode: you define routes as objects with
createBrowserRouterand render<RouterProvider>. Routes can haveloader,action,ErrorBoundaryandlazy. Still a client-side SPA, with no build plugin. - Framework mode: a Vite plugin, a
routes.tsfile and route modules with typed loaders and actions. It adds server rendering, static pre-rendering or an SPA build, and is effectively what Remix was. It competes with Next.js.
Data mode is where most of the interesting ideas live:
import { createBrowserRouter, data, redirect } from "react-router";
import { RouterProvider } from "react-router/dom";
const router = createBrowserRouter([
{
path: "/",
Component: RootLayout, // renders the nav and an <Outlet />
ErrorBoundary: RootError,
children: [
{ index: true, Component: Home },
{
path: "projects/:projectId",
loader: async ({ params, request }) => {
const res = await fetch(`/api/projects/${params.projectId}`, { signal: request.signal });
if (res.status === 404) throw data("Project not found", { status: 404 });
if (!res.ok) throw new Error(`Failed to load project: ${res.status}`);
return res.json() as Promise<Project>;
},
action: async ({ params, request }) => {
const form = await request.formData();
await api.renameProject(params.projectId!, String(form.get("name")));
return redirect(`/projects/${params.projectId}`);
},
Component: ProjectPage, // reads the result with useLoaderData()
ErrorBoundary: ProjectError, // useRouteError() + isRouteErrorResponse() to tell 404 from a crash
},
{ path: "reports", lazy: () => import("./routes/reports") }, // module exports Component, loader...
{ path: "*", Component: NotFound },
],
},
]);
createRoot(document.getElementById("root")!).render(<RouterProvider router={router} />);A <Form method="post"> inside ProjectPage submits to the route's action. After an action finishes, the router revalidates: it runs the loaders on the page again, so the screen shows the new data without you invalidating anything. useNavigation() tells you whether the router is idle, loading or submitting, for a global progress bar. useFetcher() runs an action or loader without navigating, for inline edits like a "star" button in a list.
Loaders kill request waterfalls
The biggest reason to use loaders, in any router, is timing. When each component fetches its own data in an effect or useQuery, a nested page fetches in a waterfall: the layout renders and fetches the user, then the project page renders and fetches the project, then the settings panel renders and fetches its settings. Each step waits for the one above. A router knows the whole route tree for a URL before rendering anything, so it can start every loader at once.
Matching walks the tree. The root layout matches every URL, so its loader (the current user) is always part of the match.
Loaders and TanStack Query are not rivals. A common setup is a loader that calls queryClient.ensureQueryData(projectQueries.detail(id)), so the fetch starts at navigation time, and a component that reads the same entry with useQuery, so it gets caching, background refresh and optimistic updates, as you saw in Server State with TanStack Query.
TanStack Router: type-safe params and search
TanStack Router has the same building blocks (nested routes, loaders, pending and error components) and one big difference: everything is typed. With file-based routing, its build plugin generates a route tree, and after you register the router's type once, every Link, param and search param is checked by TypeScript.
import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
const searchSchema = z.object({
tab: z.enum(["overview", "tasks", "settings"]).catch("overview"),
page: z.coerce.number().int().min(1).catch(1),
});
export const Route = createFileRoute("/projects/$projectId")({
validateSearch: (search) => searchSchema.parse(search),
loader: ({ params }) => fetchProject(params.projectId),
component: ProjectPage,
});
function ProjectPage() {
const { projectId } = Route.useParams(); // string, known to exist
const { tab, page } = Route.useSearch(); // typed and already validated
const project = Route.useLoaderData();
// ...
}
// Elsewhere: a typo in the path, a missing param or an invalid tab is a compile error.
// <Link to="/projects/$projectId" params={{ projectId: "42" }} search={{ tab: "tasks" }}>Tasks</Link>Search params are where it shines. In State Management at Scale you saw that filters, tabs and pagination belong in the URL so they survive refreshes and can be shared. Most routers hand you raw strings from URLSearchParams. TanStack Router validates the search object with your schema, so page is a number with a default, and a hand-edited URL with ?tab=banana falls back to overview instead of crashing a component. Its plugin can also split each route into its own chunk automatically; check the docs for the current option.
Code splitting, pending UI and 404s
Split by route. Users visiting the dashboard should not download the admin reports screen. Route-level splitting gives you the biggest win for the least effort. React.lazy with Suspense (from Performance) works anywhere, but it starts downloading only when the component renders. A router's lazy option is better: the router starts the code download and the loader at the same moment the navigation starts, instead of one after the other.
Pending UI. With loaders, the old page stays on screen until the new data is ready. That avoids a flash of spinners, but if a loader takes two seconds the app looks frozen. Show a global indicator from useNavigation(), and keep loaders fast by deferring slow, non-critical data so it streams in after the page renders.
404s come in two kinds. A URL matching no route at all hits the * splat. A URL that matches a pattern but points at nothing (project 99 was deleted) should be handled in the loader: throw a 404 response and render it in the route's error boundary. Both should look like a real "not found" page, not a crash.
The refresh 404. The bug from the intro: client-side routes exist only in your JavaScript. When someone refreshes /projects/42 or opens a shared link, the browser asks the server for that path, and a static host that only has index.html answers 404. The Vite dev server handles this for you, which is why it only breaks on staging. In production, configure an SPA fallback so unknown paths serve index.html:
location / {
try_files $uri $uri/ /index.html;
}Every static host has an equivalent rewrite setting; check your host's docs for "SPA fallback" or "rewrites".
Protected routes
The usual pattern: a layout route around everything that needs a signed-in user. In data mode its loader checks the session and throws redirect("/login?next=/billing") when there is none, so protected components never even render. In declarative mode, a layout component renders <Navigate to="/login" replace /> instead of its <Outlet />. Use replace, so Back does not return the user to a page that will just redirect them again. After login, send them to next, and check that it is a path on your own site, so an attacker cannot craft a login link that bounces users to a phishing page.
The most important point for interviews and for security reviews: a protected route is a user-experience feature, not security. Everything in an SPA bundle can be read by anyone who opens DevTools, and they can call your API directly. The API must check authentication and authorization on every request. The route guard only stops honest users from seeing a broken screen.
Scroll and focus: the accessibility half
A full page load gives screen reader users a clear signal: a new page title is announced and focus starts at the top. A client-side navigation gives them nothing. The DOM changes silently, focus stays on the link they clicked (which may no longer exist), and they cannot tell anything happened. Routers do not fix this by default, so it is on you.
- Move focus to the new page's main heading (with
tabIndex={-1}so script can focus it) or to the main content region, as the demo does. Do not do it on the first page load. - Update the title. In React 19 you can render
<title>inside any component and React places it in the document head. Some teams also announce the new title through a visually hidden live region. Next.js ships a built-in route announcer that does this. - Restore scroll. New pages should start at the top, and Back should return to where the user was. The browser does this for real page loads, but in an SPA the content is not there yet when it tries. React Router's
<ScrollRestoration />(data and framework modes) saves positions per history entry and restores them after rendering. TanStack Router has its own equivalent. - Unsaved changes. In Forms at Scale you guarded refreshes with
beforeunload. In-app navigation needs the router:useBlockerin React Router data mode lets you stop a navigation and ask the user to confirm.
Match each React Router tool to the job it does.
When to choose a framework instead
An SPA with a client router is a good fit for apps behind a login, internal tools and dashboards: no SEO needs, users who stay a long time, and a separate API. You pay for it on first load, since nothing shows until JavaScript downloads, runs and fetches.
Choose a framework when first load and SEO matter (marketing pages, e-commerce, content), or when you want server code next to your UI. Next.js (file-based App Router, Server Components, covered in the Next.js course's App Router Routing lesson), React Router framework mode (loaders and actions with server rendering, the Remix lineage) and TanStack Start (full stack, built on TanStack Router) all give you server rendering plus client-side navigation after the first load. That is the best of both, at the cost of running a server or a build step that knows about routes. As Project Setup said, Create React App is gone: a new SPA starts with Vite plus a router, a new server-rendered app starts with a framework.
- History API
- Browser API (
pushState,replaceState,popstate) that changes the URL and session history without reloading the page. - popstate
- Event fired when the user traverses history with Back or Forward. It does not fire for your own
pushStatecalls. - nested route
- A route rendered inside a parent layout's
<Outlet>. The parent stays mounted while children change. - loader
- A function the router calls for a matched route before rendering it, so data loads in parallel at navigation time.
- route ranking
- Choosing the most specific matching pattern (static over dynamic over splat), not the first one declared.
- SPA fallback
- Server or host rule that serves
index.htmlfor unknown paths so deep links and refreshes work. - scroll restoration
- Saving scroll position per history entry and restoring it on Back, after the new content renders.