Skip to content

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.

15 min read0/4 questions

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:

  1. Intercept clicks on internal links and call event.preventDefault().
  2. Change the URL without a reload, with history.pushState(state, "", "/projects/42").
  3. Listen for the back and forward buttons, which fire a popstate event.
  4. 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.

ReactMiniRouter.tsx
import { createContext, use, useEffect, useRef, useSyncExternalStore } from "react";import type { MouseEvent, ReactNode } from "react"; // 1. A history store. window.history works the same way, with the URL bar as its display.let snapshot = { entries: ["/"], index: 0 };const listeners = new Set<() => void>();const history = { subscribe: (l: () => void) => { listeners.add(l); return () => { listeners.delete(l); }; }, get: () => snapshot, push(path: string) { const entries = [...snapshot.entries.slice(0, snapshot.index + 1), path]; // pushing drops the forward entries snapshot = { entries, index: entries.length - 1 }; listeners.forEach((l) => l()); }, go(delta: number) { // what popstate reports for back and forward const index = Math.min(Math.max(snapshot.index + delta, 0), snapshot.entries.length - 1); snapshot = { ...snapshot, index }; listeners.forEach((l) => l()); },};const useLocation = () => { const s = useSyncExternalStore(history.subscribe, history.get); return s.entries[s.index];}; // 2. Links intercept plain left clicks only, so cmd/ctrl-click still opens a new tab.function Link({ to, children }: { to: string; children: ReactNode }) { const location = useLocation(); function onClick(e: MouseEvent<HTMLAnchorElement>) { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; e.preventDefault(); if (to !== location) history.push(to); } return <a href={to} onClick={onClick} aria-current={location === to ? "page" : undefined} style={{ marginRight: 12 }}>{children}</a>;} // 3. Matching and nested rendering.const PROJECTS: Record<string, string> = { "1": "Billing revamp", "2": "Mobile onboarding" };const OutletContext = createContext<ReactNode>(null);const Outlet = () => use(OutletContext); function matchChild(path: string): ReactNode { const [section, id, ...rest] = path.split("/").filter(Boolean); if (!section) return <><h1 tabIndex={-1}>Home</h1><p>Pick a section above.</p></>; if (section === "projects" && !id) return ( <><h1 tabIndex={-1}>Projects</h1> <ul>{Object.entries(PROJECTS).map(([pid, name]) => <li key={pid}><Link to={`/projects/${pid}`}>{name}</Link></li>)}</ul> </> ); if (section === "projects" && id && rest.length === 0) { return PROJECTS[id] ? <><h1 tabIndex={-1}>{PROJECTS[id]}</h1><p>Route param: id = {id}</p></> : <><h1 tabIndex={-1}>Project not found</h1><p>No project with id {id}.</p></>; } return <><h1 tabIndex={-1}>404: page not found</h1><p>Nothing matches {path}.</p></>;} function Layout() { const location = useLocation(); const main = useRef<HTMLElement>(null); const first = useRef(true); useEffect(() => { // 4. after navigating, move focus to the new heading (not on first load) if (first.current) { first.current = false; return; } main.current?.querySelector("h1")?.focus(); }, [location]); return ( <div> <nav aria-label="Main"><Link to="/">Home</Link><Link to="/projects">Projects</Link><Link to="/projects/99">Project 99</Link><Link to="/nope">Broken link</Link></nav> <main ref={main} style={{ borderTop: "1px solid #ccc", marginTop: 8 }}><Outlet /></main> </div> );} export default function App() { const location = useLocation(); const { entries, index } = useSyncExternalStore(history.subscribe, history.get); return ( <div> <div style={{ display: "flex", gap: 6, marginBottom: 8 }}> <button onClick={() => history.go(-1)} disabled={index === 0}>Back</button> <button onClick={() => history.go(1)} disabled={index === entries.length - 1}>Forward</button> <code style={{ alignSelf: "center" }}>URL: {location}</code> </div> <OutletContext value={matchChild(location)}> <Layout /> </OutletContext> <small>History: {entries.map((e, i) => (i === index ? `[${e}]` : e)).join(" ")}</small> </div> );}

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:

TypeScriptmatch-routes.ts
type Match = { pattern: string; params: Record<string, string>; score: number }; // Static segment 3 points, dynamic 2, splat 1. Highest score wins.function matchPath(pattern: string, path: string): Match | null { const want = pattern.split("/").filter(Boolean); const got = path.split("/").filter(Boolean); const params: Record<string, string> = {}; let score = 0; for (let i = 0; i < want.length; i++) { if (want[i] === "*") { params["*"] = got.slice(i).join("/"); return { pattern, params, score: score + 1 }; } if (i >= got.length) return null; if (want[i].startsWith(":")) { params[want[i].slice(1)] = decodeURIComponent(got[i]); score += 2; } else if (want[i] === got[i]) { score += 3; } else { return null; } } return want.length === got.length ? { pattern, params, score } : null;} const routes = ["*", "/projects/:projectId", "/projects/new", "/projects/:projectId/settings"]; function resolve(path: string): Match { const matches = routes.map((r) => matchPath(r, path)).filter((m): m is Match => m !== null); return matches.sort((a, b) => b.score - a.score)[0];} for (const path of ["/projects/new", "/projects/42", "/projects/42/settings", "/projects/a%20b", "/teams/7"]) { const m = resolve(path); console.log(path.padEnd(22), "->", m.pattern.padEnd(30), JSON.stringify(m.params));}
Output
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.

Predict the outputTypeScript

Using the matcher and routes above, which pattern wins for this path?

console.log(resolve("/projects/new/settings").pattern);
Need a nudge? Hints walk you through it.

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 createBrowserRouter and render <RouterProvider>. Routes can have loader, action, ErrorBoundary and lazy. Still a client-side SPA, with no build plugin.
  • Framework mode: a Vite plugin, a routes.ts file 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:

src/router.tsx
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 /projects/42/settings against a route tree
/RootLayout: nav, user menu, OutletindexHomeindexproject listindexoverview tabsettingssettings tab:projectIdProjectPage: header, tabs, OutletprojectsProjectsLayout: sidebar, Outlet*NotFoundroot

Matching walks the tree. The root layout matches every URL, so its loader (the current user) is always part of the match.

1/4

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.

Put it in order6 steps

In React Router data mode, a user clicks a link to /projects/42/settings. Order what happens.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

src/routes/projects.$projectId.tsx
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:

nginx.conf
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.

Quick check
An admin page is protected by a route guard that redirects non-admins to /home. What actually stops a non-admin from reading admin data?
Need a nudge? A hint rules out a wrong answer.

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: useBlocker in React Router data mode lets you stop a navigation and ask the user to confirm.
Match the pairs0/6 matched

Match each React Router tool to the job it does.

Choose an item, then its match on the other side.

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.

Key terms
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 pushState calls.
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.html for 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.