Routing

React Router and TanStack Router outside Next.js.

Builds on Starting a React app.

The previous chapter ended on a claim: the URL should decide which code and data a screen needs, so whatever owns the URL should coordinate them. In Next.js that's the file system and the App Router. Outside Next.js it's a router library, and in 2026 that mostly means React Router (now on v8) or TanStack Router.

This chapter builds a client-side router from nothing, so you can say exactly what one does, then maps it onto React Router's three modes and TanStack Router. The part interviewers care about most is the step from "a router renders the right component" to "a router loads the right data before rendering", so that gets the most space.

The problem: screens without URLs#

The simplest way to have several screens is a piece of state that says which one is showing. Click around, then look at the URL bar above the preview.

Routing with useState
import { useState } from "react";
import { books } from "guide-tools";

type Screen = { name: "home" } | { name: "books" } | { name: "book"; id: number };

export default function App() {
  const [screen, setScreen] = useState<Screen>({ name: "home" });
  return (
    <div>
      <nav style={{ display: "flex", gap: 12 }}>
        <button onClick={() => setScreen({ name: "home" })}>Home</button>
        <button onClick={() => setScreen({ name: "books" })}>Books</button>
      </nav>
      {screen.name === "home" && <p>Welcome to your reading list.</p>}
      {screen.name === "books" && (
        <ul>
          {books.slice(0, 4).map((b) => (
            <li key={b.id}>
              <button onClick={() => setScreen({ name: "book", id: b.id })}>{b.title}</button>
            </li>
          ))}
        </ul>
      )}
      {screen.name === "book" && <p>{books.find((b) => b.id === screen.id)?.title}</p>}
    </div>
  );
}

It works, and the URL never changes. That breaks a list of things users expect from the web: you can't share a link to a book, refresh puts you back on the home screen, the back button leaves the app entirely, you can't open a book in a new tab, and search engines see one page. The URL is state, and it's the one piece of state the browser, the user and other people all share. A router's first job is to make the URL the source of truth for which screen is showing.

Build a tiny router#

A client-side router needs four pieces. The sandbox's URL bar is virtual (a sandboxed iframe can't change its real URL), but history.pushState is captured and useVirtualLocation from guide-tools subscribes to it, exactly like a router subscribes to the real one.

A router in 50 lines
import { createContext, useContext, type MouseEvent, type ReactNode } from "react";
import { books, useVirtualLocation } from "guide-tools";

// 1. Navigate: change the URL without loading a page.
function navigate(to: string) {
  history.pushState(null, "", to);
}

// 2. Read the URL: subscribe to location changes (useSyncExternalStore inside).
function usePathname() {
  return new URL(useVirtualLocation()).pathname;
}

// 3. Link: a real <a>, with the browser's own navigation cancelled.
function Link({ to, children }: { to: string; children: ReactNode }) {
  function onClick(e: MouseEvent<HTMLAnchorElement>) {
    // Let the browser handle new-tab clicks and other modified clicks.
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    e.preventDefault();
    navigate(to);
  }
  return <a href={to} onClick={onClick}>{children}</a>;
}

// 4. Match: "/books/:id" against "/books/3" gives { id: "3" }.
function matchPath(pattern: string, pathname: string): Record<string, string> | null {
  const want = pattern.split("/").filter(Boolean);
  const got = pathname.split("/").filter(Boolean);
  if (want.length !== got.length) return null;
  const params: Record<string, string> = {};
  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;
}

const ParamsContext = createContext<Record<string, string>>({});
const useParams = () => useContext(ParamsContext);

function Router({ routes }: { routes: { path: string; element: ReactNode }[] }) {
  const pathname = usePathname();
  for (const route of routes) {
    const params = matchPath(route.path, pathname);
    if (params) return <ParamsContext value={params}>{route.element}</ParamsContext>;
  }
  return <p>No route matches {pathname}</p>;
}

// ---- The app ----
function BookList() {
  return (
    <ul>
      {books.slice(0, 4).map((b) => (
        <li key={b.id}>
          <Link to={`/books/${b.id}`}>{b.title}</Link>
        </li>
      ))}
    </ul>
  );
}

function BookDetail() {
  const { id } = useParams();
  const book = books.find((b) => b.id === Number(id)); // params are strings
  return book ? <p>{book.title}, by {book.author}</p> : <p>No book {id}</p>;
}

export default function App() {
  return (
    <div>
      <nav style={{ display: "flex", gap: 12 }}>
        <Link to="/">Home</Link>
        <Link to="/books">Books</Link>
      </nav>
      <Router
        routes={[
          { path: "/", element: <p>Welcome to your reading list.</p> },
          { path: "/books", element: <BookList /> },
          { path: "/books/:id", element: <BookDetail /> },
        ]}
      />
    </div>
  );
}

Now the URL bar follows you, and every screen has an address. That's the whole trick of client-side routing: change the URL without a document load, and re-render from the URL. Everything a real router adds sits on top of this loop.

One client-side navigation
Click on <a href>a normal linkpreventDefault()no request, no reloadhistory.pushState()URL changes, page staysNotify subscribersthe router's location storeMatch routespattern → paramsRender the matchplain React re-renderBack buttonbrowser fires popstate
Step 1 of 7

A client-side router starts with an ordinary anchor, so the link still works with a middle click, a right click, or before JavaScript loads.

What our toy is missing, and what real routers add:

  • Back and forward. The browser fires popstate when the user goes back. A real router listens for it and re-renders. (The sandbox's virtual URL has no back button, so we skipped it.)
  • Nested routes and layouts. Our routes are flat. Real apps have a shell that stays mounted while the inner part changes, which needs a way for a parent to say "render the matched child here".
  • Ranking. We take the first match. Real routers rank patterns so /books/new beats /books/:id regardless of order.
  • Search params, relative links, scroll restoration, focus management, blocking navigation with unsaved changes.
  • Data. The biggest one. Our BookDetail reads from an in-memory array. Real pages fetch, and if each page fetches in an effect after it renders, you get the waterfalls from the last chapter.

React Router v8#

React Router is the most used router for React. Its history matters for understanding the API: v6 introduced nested routes with <Outlet>, v6.4 added data loading (loaders and actions, ported from the Remix framework), and v7 merged Remix itself into React Router as framework mode. v8, the current major (8.5.3), turns v7's opt-in future flags into defaults (middleware, split route modules, Vite's Environment API), requires React 19.2.7 or later, and drops the separate react-router-dom package: everything imports from react-router, with DOM-only pieces in react-router/dom.

It comes in three modes. Each adds features on top of the previous one, and you pick one per app:

ModeYou writeIt adds
Declarative<BrowserRouter>, <Routes>, <Route> in JSXMatching, nested routes, links, params
DataRoute objects passed to createBrowserRouter, rendered by <RouterProvider>loader, action, pending UI, error boundaries, revalidation
FrameworkA routes.ts file and route modules, through a Vite pluginType generation, code splitting per route, SSR, prerendering, SPA mode

Declarative mode: matching and nesting#

The sandbox can't change the real URL, so these examples use the memory variants (MemoryRouter, createMemoryRouter), which keep history in an array instead of the address bar. In an app you'd use BrowserRouter or createBrowserRouter. Because the memory router doesn't touch history, the sandbox's URL bar stays put; the examples print the location instead.

Nested routes with Outlet
import { MemoryRouter, Routes, Route, NavLink, Link, Outlet, useParams, useLocation } from "react-router";
import { books } from "guide-tools";
import "./styles.css";

function Shell() {
  const { pathname } = useLocation();
  return (
    <div>
      <nav style={{ display: "flex", gap: 12 }}>
        <NavLink to="/" end>Home</NavLink>
        <NavLink to="/books">Books</NavLink>
      </nav>
      <p style={{ color: "#78716c", fontSize: 13 }}>location: {pathname}</p>
      <Outlet />
    </div>
  );
}

function BookList() {
  return (
    <div style={{ display: "flex", gap: 24 }}>
      <ul>
        {books.slice(0, 4).map((b) => (
          <li key={b.id}>
            <Link to={String(b.id)}>{b.title}</Link>
          </li>
        ))}
      </ul>
      <Outlet />
    </div>
  );
}

function BookDetail() {
  const { id } = useParams();
  const book = books.find((b) => b.id === Number(id));
  return <p>{book ? `${book.title} (${book.year})` : "Not found"}</p>;
}

export default function App() {
  return (
    <MemoryRouter initialEntries={["/books"]}>
      <Routes>
        <Route element={<Shell />}>
          <Route index element={<p>Welcome to your reading list.</p>} />
          <Route path="books" element={<BookList />}>
            <Route index element={<p>Pick a book.</p>} />
            <Route path=":id" element={<BookDetail />} />
          </Route>
          <Route path="*" element={<p>Nothing here.</p>} />
        </Route>
      </Routes>
    </MemoryRouter>
  );
}

Read the route tree as a tree of layouts. /books/3 matches three routes at once: the pathless Shell route, books, and :id. React Router renders Shell, and wherever Shell puts <Outlet />, it renders the next match (BookList), whose own <Outlet /> renders BookDetail. Navigating from book 3 to book 4 only changes the innermost element, so Shell and BookList keep their state and DOM. index routes render at their parent's exact path, and NavLink adds an active class and aria-current="page" when its target matches. The styles.css import makes the active link bold; the sandbox injects imported CSS files the way a bundler would.

Data mode: loaders, actions and pending UI#

Declarative mode still leaves data fetching inside components. Data mode moves it into the route definition, which is the point the last chapter was building to. You define routes as objects outside React, each with an optional loader (runs before the route renders, on every navigation to it) and action (runs when a form submits to it). The router:

  1. Matches the URL to a branch of routes before rendering.
  2. Calls every matched route's loader in parallel.
  3. Renders once the data is ready, with useLoaderData() returning each route's result.
  4. On a <Form method="post"> submission, calls the route's action, then revalidates the loaders on the page, so the UI shows fresh data without a manual refetch.

Open the console, then click around and add a book.

A reading list in data mode
import {
  createMemoryRouter,
  RouterProvider,
  Outlet,
  NavLink,
  Link,
  Form,
  redirect,
  useLoaderData,
  useNavigation,
  useLocation,
  useRouteError,
  type LoaderFunctionArgs,
  type ActionFunctionArgs,
} from "react-router";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string; author: string; year: number };
const t0 = performance.now();
const at = () => Math.round(performance.now() - t0) + "ms";

// ---- Loaders and actions: plain async functions, outside React ----
async function rootLoader() {
  console.log("root loader starts at", at());
  return { user: await fakeFetch("/users/1") };
}

async function booksLoader() {
  console.log("books loader starts at", at());
  return { books: (await fakeFetch("/books")) as Book[] };
}

async function bookLoader({ params }: LoaderFunctionArgs) {
  console.log(`book ${params.id} loader starts at`, at());
  return { book: (await fakeFetch(`/books/${params.id}`)) as Book };
}

async function addBook({ request }: ActionFunctionArgs) {
  const form = await request.formData();
  console.log("action starts at", at());
  await fakeFetch("/books", {
    method: "POST",
    body: { title: String(form.get("title")), author: "You", year: 2026, tags: [] },
  });
  return redirect("/books");
}

// ---- Route components ----
function Root() {
  const { user } = useLoaderData<typeof rootLoader>();
  const navigation = useNavigation();
  const { pathname } = useLocation();
  return (
    <div>
      <nav style={{ display: "flex", gap: 12 }}>
        <NavLink to="/books" end>Books</NavLink>
        <NavLink to="/books/new">Add a book</NavLink>
        <Link to="/books/999">A missing book</Link>
      </nav>
      <p style={{ color: "#78716c", fontSize: 13 }}>
        {user.name} · {pathname} · navigation.state = "{navigation.state}"
      </p>
      <div style={{ opacity: navigation.state === "loading" ? 0.5 : 1 }}>
        <Outlet />
      </div>
    </div>
  );
}

function BookList() {
  const { books } = useLoaderData<typeof booksLoader>();
  return (
    <ul>
      {books.map((b) => (
        <li key={b.id}>
          <Link to={`/books/${b.id}`}>{b.title}</Link>
        </li>
      ))}
    </ul>
  );
}

function BookDetail() {
  const { book } = useLoaderData<typeof bookLoader>();
  return (
    <p>
      {book.title}, by {book.author} ({book.year})
    </p>
  );
}

function NewBook() {
  const navigation = useNavigation();
  const saving = navigation.state === "submitting";
  return (
    <Form method="post">
      <label>
        Title <input name="title" required />
      </label>{" "}
      <button disabled={saving}>{saving ? "Saving…" : "Add"}</button>
    </Form>
  );
}

function BookError() {
  const error = useRouteError() as Error;
  return <p style={{ color: "#b4532a" }}>Couldn't load that book: {error.message}</p>;
}

// ---- The route tree, created once, outside React ----
const router = createMemoryRouter(
  [
    {
      path: "/",
      Component: Root,
      loader: rootLoader,
      HydrateFallback: () => <p>Loading…</p>,
      children: [
        { path: "books", Component: BookList, loader: booksLoader },
        { path: "books/new", Component: NewBook, action: addBook },
        { path: "books/:id", Component: BookDetail, loader: bookLoader, ErrorBoundary: BookError },
      ],
    },
  ],
  { initialEntries: ["/books"] },
);

export default function App() {
  return <RouterProvider router={router} />;
}
Nothing logged yet.

Things to look for:

  • On the first load, the root loader and the books loader start at the same millisecond. The router knew both routes from the URL before rendering anything, so there's no waterfall. That's the fix from the last chapter, built into the router.
  • While a navigation's loaders run, the old page stays on screen and navigation.state is "loading". You decide the pending UI (here, dimming). This is the router's version of a transition: keep showing old content until the new content is ready.
  • Submitting the form sets navigation.state to "submitting", runs addBook, follows the redirect and revalidates. The new book appears because the router re-ran the loaders, not because anyone updated a cache by hand. It's the same mental model as a Server Action followed by revalidation in Next.js.
  • /books/999 throws in its loader, and the nearest ErrorBoundary on the route tree renders in that route's slot. The shell keeps working.
  • useLoaderData<typeof bookLoader>() infers the return type of the loader. In framework mode, generated types make this automatic.
Who starts the fetch
useEffect in componentsuserbooksGET /users/1GET /booksrenders0 ms400 ms800 msdata complete at 800 ms
Step 1 of 3

Fetching in effects. App renders, then its effect requests the user. Books only exists after the user arrives, so its request starts at 400 ms. Each level of nesting adds a round trip.

PredictWhich loaders run?

In the data-mode sandbox above, the app starts on /books. Predict which loaders log to the console for each step, in order: (1) click The Pragmatic Programmer; (2) click Books in the nav; (3) go to Add a book and submit a title. Then run it and check.

Framework mode#

Framework mode is data mode plus a Vite plugin and conventions. You list routes in app/routes.ts, and each route is a route module that exports its loader, action, component, error boundary and metadata. The plugin generates types per route, splits code per route automatically, and can render on the server, prerender at build time, or build a pure SPA. This can't run in the sandbox, so here it is as static code.

app/routes.ts
import { type RouteConfig, index, layout, route } from "@react-router/dev/routes";

export default [
  layout("./routes/shell.tsx", [
    index("./routes/home.tsx"),
    route("books", "./routes/books.tsx"),
    route("books/:id", "./routes/book.tsx"),
  ]),
] satisfies RouteConfig;

The ./+types/book import is generated by the plugin from routes.ts, which is how params.id and loaderData get exact types without you writing them. Files named *.server.ts are kept out of the client bundle. Compare this with the Next.js App Router you know: both put data loading at the route level and both render on the server. React Router's loaders are plain functions returning data (with a clientLoader option for browser-only data), while Next.js leans on Server Components that fetch inside the tree. React Router also has unstable RSC support, but loaders are the main model.

TanStack Router: types first#

TanStack Router reaches the same capabilities (nested routes, loaders, pending states, code splitting) with one priority above everything: every route, param and search param is fully typed. A link to a route that doesn't exist, or a missing param, is a compile error, not a 404 found in production.

src/routes/books.$bookId.tsx
import { createFileRoute, Link } from "@tanstack/react-router";
import { z } from "zod";
import { fetchBook } from "../api";

export const Route = createFileRoute("/books/$bookId")({
  // Search params are validated and typed, like a form.
  validateSearch: z.object({
    tab: z.enum(["details", "reviews"]).catch("details"),
  }),
  loader: ({ params }) => fetchBook(params.bookId),
  component: BookPage,
});

function BookPage() {
  const book = Route.useLoaderData(); // typed from the loader
  const { tab } = Route.useSearch(); // "details" | "reviews"
  return (
    <>
      <h1>{book.title}</h1>
      <Link to="/books/$bookId" params={{ bookId: String(book.id) }} search={{ tab: "reviews" }}>
        Reviews
      </Link>
      {tab === "reviews" ? <Reviews bookId={book.id} /> : <Details book={book} />}
    </>
  );
}

A typo shows the payoff:

<Link to="/book/$bookId" params={{ bookId: "3" }}>Book</Link>
// error TS2322: Type '"/book/$bookId"' is not assignable to type
//   '"/" | "/books" | "/books/$bookId" | ...'.   (abridged)

TanStack Router treats search params as first-class, typed state, which suits apps with lots of filters, sorts and pagination in the URL (the URL and form state chapter). The cost is a code generator in your build and more TypeScript machinery. TanStack Start is the full-stack framework built on it, the way React Router's framework mode is built on its data mode.

Pitfalls#

Check your understanding#

Build itImplement matchPath

The toy router's matcher has been replaced by one that only matches exact strings, so book pages don't work. Implement matchPath in matchPath.ts: split both strings into segments, require the same number of segments, treat segments starting with : as params (decoded, as strings), and require every other segment to be equal.

export function matchPath(pattern: string, pathname: string): Record<string, string> | null {
  // TODO: support :params
  return pattern === pathname ? {} : null;
}

(window as any).matchPath = matchPath; // for the checks
Fix itThe book page never shows

This app uses React Router's declarative mode. Clicking Books works, but clicking a book title changes nothing visible, and even when it does, the detail says "Not found". There are two bugs.

import { MemoryRouter, Routes, Route, Link, Outlet, useParams } from "react-router";
import { books } from "guide-tools";

function Shell() {
  return (
    <div>
      <nav style={{ display: "flex", gap: 12 }}>
        <Link to="/">Home</Link>
        <Link to="/books">Books</Link>
      </nav>
      <Outlet />
    </div>
  );
}

function BookList() {
  return (
    <div>
      <ul>
        {books.slice(0, 4).map((b) => (
          <li key={b.id}>
            <Link to={`/books/${b.id}`}>{b.title}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

function BookDetail() {
  const { id } = useParams();
  const book = books.find((b) => b.id === (id as unknown));
  return <p>{book ? `${book.title} was published in ${book.year}` : "Not found"}</p>;
}

export default function App() {
  return (
    <MemoryRouter initialEntries={["/"]}>
      <Routes>
        <Route element={<Shell />}>
          <Route index element={<p>Welcome</p>} />
          <Route path="books" element={<BookList />}>
            <Route path=":id" element={<BookDetail />} />
          </Route>
        </Route>
      </Routes>
    </MemoryRouter>
  );
}
Quick checkWhere the router lives

Why should `createBrowserRouter` be called at module level instead of inside a component?

Explain it out loudExplain client-side routing

An interviewer asks: "How does client-side routing work, and why do modern routers have loaders?"

Interview angle

Say it in 30 seconds

A client-side router makes the URL the source of truth for which screen shows. It intercepts link clicks, calls history.pushState so no document loads, keeps the location in a store React subscribes to, matches the path against route patterns to get params, and renders the matched routes, nesting children through Outlet. Modern routers go further: React Router's data mode and TanStack Router match the URL before rendering, call every matched route's loader in parallel, show pending UI, and revalidate after form actions. That removes fetch-in-effect waterfalls and manual refetching.

How does client-side routing work under the hood?

basic

Why do routers like React Router have loaders instead of fetching in components?

intermediate

What are nested routes, and what does Outlet do?

basic

What happens after a form submits to a route action in React Router?

senior

React Router or TanStack Router: how do they differ?

senior

What changed in React Router v7 and v8?

intermediate

Recap#

  • Client-side routing is a loop: intercept the click, pushState, notify subscribers, match the pathname to a pattern, render. popstate handles back and forward.
  • The URL is shared state, so screens need real addresses: links, refresh, back, new tabs and crawlers all depend on it.
  • React Router v8 has three modes. Declarative matches and nests routes with <Outlet>; data mode adds loaders, actions, useNavigation and error boundaries; framework mode adds a Vite plugin, generated types, per-route splitting, SSR and prerendering.
  • Loaders run in parallel before rendering, which removes fetch-in-effect waterfalls. Actions plus automatic revalidation replace manual refetching after mutations.
  • TanStack Router offers the same loading model with fully typed routes, params and search params, at the cost of a code generator and heavier types.

Sources#