Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 132 ยท Routing and Apps

React Router and Framework Routers

Learn React Router and framework routers: route config, nested layouts, loaders, actions, forms, pending state and framework mode, with runnable mini versions.

In Client-Side Routing you built a router that reads the URL, matches a pattern, renders a component and updates on navigation. That is the foundation. Modern routers go much further: they treat the route as the place where data loading, mutations, errors and pending states are organized, so each screen does not have to reinvent them with useEffect.

This lesson explains what React Router (the most widely used router, now at version 7) and its competitors offer, how their route config, loaders and actions work, and what "framework mode" adds. Because the editor cannot install packages, the real library code appears in read-only blocks, clearly marked, and every idea also has a runnable hand-written stand-in so you can see the mechanics. The stand-ins are teaching tools, not replacements for the library.

The landscape

Router Style Notes
React Router 7 Route config or file-based, loaders and actions The most popular. The package is react-router; older code imports from react-router-dom, which re-exports it. Three modes: declarative, data and framework.
TanStack Router File-based or code, fully type-safe Typed params and search params, built-in search param validation, first-class caching with TanStack Query.
Next.js App Router File-system routing in a full-stack framework Server Components, nested layouts and loading files. See Server Components, Server Functions and Frameworks.
Wouter, Reach-style tiny routers Minimal API A few KB, good for small apps, no data layer.

React Router's three modes are worth understanding because the docs and tutorials mix them:

  1. Declarative mode (<BrowserRouter> with <Routes> and <Route>): matching and navigation only, like the router you built.
  2. Data mode (createBrowserRouter and RouterProvider): the route objects can have loader, action and errorElement.
  3. Framework mode: a build tool plugin (with Vite) that generates routes from a config file, adds type-safe route modules, server rendering, code splitting and more. It is the successor to Remix.

Route configuration and matching

Routes are data: an array of objects with a path, an element and optional children. Nested objects mean nested URLs and nested UI, exactly like the layout and Outlet pattern you built. This is the real library API (read-only: it needs npm install react-router):

JSX
// main.jsx - React Router data mode (read-only)
import { createBrowserRouter, RouterProvider, Outlet, NavLink } from 'react-router';

function Root() {
  return (
    <div>
      <nav>
        <NavLink to="/" end>Home</NavLink>
        <NavLink to="/users">Users</NavLink>
      </nav>
      <Outlet />
    </div>
  );
}

const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    errorElement: <RootError />,
    children: [
      { index: true, element: <Home /> },
      { path: 'users', element: <UsersLayout />, children: [
        { index: true, element: <UserList /> },
        { path: ':userId', element: <UserDetail /> },
      ] },
      { path: '*', element: <NotFound /> },
    ],
  },
]);

createRoot(document.getElementById('root')).render(<RouterProvider router={router} />);

Some differences from our toy router, and each is a feature you would otherwise write:

  • index: true is the index route. end on a NavLink stops "Home" from being active on every URL.
  • NavLink sets aria-current="page" and an active class, and also a pending class while its route is loading.
  • Routes are ranked by specificity (static segments beat params, params beat splats), so the order of the array does not decide the winner. The next example shows how that ranking works.
Ranking routes and building paths

/users/new matches both /users/:id and /users/new, but the static pattern scores higher, so new is not mistaken for a user id even though /users/:id is listed first. The splat /files/* captures everything after files/ as the param *, and /* is the last-resort 404. generatePath goes the other way, filling :id and encoding the value, so links are built from patterns rather than hand-assembled strings. React Router exports a function of the same name.

  • <Link to="/users/5"> renders an <a>, intercepts plain left-clicks and performs a client-side navigation. It lets the browser handle modified clicks and target="_blank". Add replace to replace the history entry, or state={...} to pass data that is not in the URL.
  • useNavigate() returns a function for navigation from code: navigate('/dashboard'), navigate(-1) for Back, navigate('/x', { replace: true }). Prefer it for results of events ("after saving"), not for ordinary links.
  • <Navigate to="/login" replace /> renders a redirect, and redirect('/login') does the same inside a loader or action.
  • Relative links resolve against the route tree, not the URL: inside the route users/:userId, <Link to="edit"> goes to /users/5/edit, and <Link to=".."> goes to the parent route.
JSX
// Navigation APIs (read-only)
import { Link, useNavigate, Navigate } from 'react-router';

function SaveButton({ userId }) {
  const navigate = useNavigate();

  async function handleSave() {
    await saveUser(userId);
    navigate('/users/' + userId, { replace: true });
  }

  return <button type="button" onClick={handleSave}>Save</button>;
}

function Guard({ isSignedIn, children }) {
  return isSignedIn ? children : <Navigate to="/login" replace />;
}

Search params

The query string is real state. React Router's useSearchParams works like useState for it: it returns the current URLSearchParams and a setter that navigates:

JSX
// Search params (read-only)
import { useSearchParams } from 'react-router';

function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();
  const sort = searchParams.get('sort') ?? 'name';

  return (
    <select
      value={sort}
      onChange={(event) => setSearchParams({ sort: event.target.value })}
    >
      <option value="name">Name</option>
      <option value="price">Price</option>
    </select>
  );
}

Values are always strings, so convert and validate them. TanStack Router goes further: you declare a schema for the search params, and they become typed and validated automatically.

Loaders: data before render

With useEffect, a page renders first, then fetches, then renders again, and nested pages create a waterfall: the parent loads, then the child starts loading. A loader is a function attached to a route. The router calls the loaders for all matched routes in parallel before showing the new screen, and a component reads the result with useLoaderData(). The component can be written as if the data were always there. This is the read-only shape:

JSX
// A loader (read-only: needs react-router and a real API)
const router = createBrowserRouter([
  {
    path: '/users/:userId',
    loader: async ({ params, request }) => {
      const response = await fetch('/api/users/' + params.userId, { signal: request.signal });
      if (response.status === 404) {
        throw new Response('Not found', { status: 404 });
      }
      return response.json();
    },
    element: <UserDetail />,
    errorElement: <UserError />,
  },
]);

function UserDetail() {
  const user = useLoaderData();
  return <h1>{user.name}</h1>;
}

Notice three things. The loader receives params and the Request (so it can read the search params and use request.signal to cancel stale work, which fixes the race conditions from Async Patterns and Race Conditions). Throwing from a loader sends the router to the nearest errorElement. And during a transition, useNavigation().state reports "loading" so you can show a progress bar while the old page stays visible.

The runnable stand-in below implements the same ideas in about 100 lines: a router with route objects, loaders called in parallel, useLoaderData, useNavigation, useParams and error handling through useRouteError, with simulated latency instead of network. (Data comes from an in-memory table, and the delays are fixed short timeouts.)

A mini data router: loaders, pending state, errors

Click "Ada". For about 150 ms the "Loading..." text appears (rendered by the Pending component, which you would normally put in a layout), the previous page fades and, when the loader finishes, the user appears with no half-empty intermediate state. "Unknown user" makes the loader throw; the router then shows the route's errorElement, Could not load this page: User 99 not found, instead of the normal element. The latest ref is a request counter: a slow, earlier navigation can never overwrite a newer one. Real routers do the same, and also cancel the old loader through an abort signal.

Loaders run on every navigation to the route, and again after actions, so a loader is a good place for a cache (TanStack Query, or the clientLoader caching in framework mode). See Caching and Server State.

Actions and forms: mutations

The mirror image of a loader is an action: a function that runs when a form is submitted to the route. React Router's <Form method="post"> serializes the fields, calls the action, then automatically revalidates: it re-runs the loaders of the visible routes, so lists and counters on screen update without you managing cache invalidation by hand. An action can return redirect('/somewhere') to finish by moving the user.

JSX
// An action (read-only)
import { Form, redirect, useActionData, useNavigation } from 'react-router';

async function createUserAction({ request }) {
  const formData = await request.formData();
  const name = String(formData.get('name') ?? '').trim();
  if (name === '') {
    return { error: 'Name is required' };
  }
  const user = await api.createUser({ name });
  return redirect('/users/' + user.id);
}

function NewUser() {
  const actionData = useActionData();
  const navigation = useNavigation();
  const isSubmitting = navigation.state === 'submitting';

  return (
    <Form method="post">
      <label>Name <input name="name" /></label>
      {actionData?.error && <p role="alert">{actionData.error}</p>}
      <button type="submit" disabled={isSubmitting}>Create</button>
    </Form>
  );
}

The form works without JavaScript too (a normal HTML form post) when the route is also handled on a server, which is the "progressive enhancement" idea behind Form Actions in React 19. Here is a runnable version of the full cycle: a form, an action that validates and writes to an in-memory list, a redirect, and the loader that re-reads the list after the mutation.

A mini action: form, validation, redirect, revalidate

Open "New note" and press "Add" with an empty field: the action returns { error } and the message Please write something. appears without leaving the page. Type a note and submit: the button is disabled during the "submitting..." state, the action logs Action saved: ..., then it redirects to the list, where the loader runs again (the console shows Loader runs for /notes (revision 1)) and the new note is there. That last step is the key idea: you never copy the new note into some client-side list; the route re-reads the source of truth.

Error boundaries, 404s and pending UI

Routers make three common screens routine:

  • errorElement (data mode) or an exported ErrorBoundary (framework mode) catches errors thrown while rendering or in loaders and actions for that route and its children. Place one on the root for the "Something went wrong" page, and more specific ones where the rest of the page should survive. Inside it, useRouteError() gives you the error and isRouteErrorResponse(error) tells apart a thrown Response (like a 404) from a crash. The underlying mechanism is the one explained in Error Boundaries.
  • 404 pages are the * route. A missing record (a valid URL but no such user) is different: throw a 404 Response from the loader.
  • Pending UI. useNavigation() for page-level state ("loading", "submitting"), useFetcher() for background mutations that should not navigate (a "like" button), and <Await> with deferred promises to stream slow data while the fast parts show immediately.

Framework mode: routes from files

In framework mode you declare your routes in a file (or let the folder structure do it), and each route is a module that exports its parts. The build tool then splits the code per route, can render on the server, generates types for params and loader data, and wires up forms. A route config looks like this (read-only; app/routes.ts in a framework-mode project):

TypeScript
import { type RouteConfig, index, route, layout } from '@react-router/dev/routes';

export default [
  index('routes/home.tsx'),
  layout('routes/app-layout.tsx', [
    route('users', 'routes/users.tsx'),
    route('users/:userId', 'routes/user.tsx'),
  ]),
  route('*', 'routes/not-found.tsx'),
] satisfies RouteConfig;

And a route module (read-only):

TSX
// app/routes/user.tsx
import type { Route } from './+types/user';

export async function loader({ params }: Route.LoaderArgs) {
  const user = await db.users.find(params.userId);
  if (!user) {
    throw new Response('Not found', { status: 404 });
  }
  return { user };
}

export default function User({ loaderData }: Route.ComponentProps) {
  return <h1>{loaderData.user.name}</h1>;
}

export function ErrorBoundary() {
  return <p>That user does not exist.</p>;
}

The Route types are generated from the config, so params.userId is known to exist and loaderData is typed from the loader's return value: rename a param and TypeScript flags every use. The loader runs on the server for the first request and, by default, on the server for client navigations too; clientLoader runs in the browser when you need local caches.

Many frameworks (and the TanStack Router) also support file-based routing, where the file names are the route table. The following runnable example converts a dictionary of file names into a route tree, with the same conventions as the common ones: $id is a param, _index is the index route, and dots become slashes.

File names to route patterns

The table shows how users.$userId.edit.tsx becomes /users/:userId/edit, _index files become the parent's own path, and $.tsx becomes a splat. In most frameworks a parent such as users.tsx is also the layout for the files whose names start with users.; you have already seen that idea in the Outlet example. The conventions differ between tools (Next.js uses folders and page.tsx, TanStack Router uses $userId and __root), so always read the docs of the one you use.

TanStack Router in one minute

TanStack Router's pitch is type safety all the way through. Read-only sketch:

TSX
import { createFileRoute, Link } from '@tanstack/react-router';

export const Route = createFileRoute('/users/$userId')({
  validateSearch: (search: Record<string, unknown>) => ({
    tab: search.tab === 'posts' ? 'posts' : 'info',
  }),
  loader: ({ params }) => fetchUser(params.userId),
  component: UserPage,
});

function UserPage() {
  const user = Route.useLoaderData();
  const { tab } = Route.useSearch();
  return (
    <div>
      <h1>{user.name}</h1>
      <Link to="/users/$userId" params={{ userId: user.id }} search={{ tab: 'posts' }}>Posts</Link>
      <p>Current tab: {tab}</p>
    </div>
  );
}

A Link with a wrong route or a missing param is a compile error, and search params have a validated type. The cost is more setup and a code generator for the route tree.

Choosing a router

  • A small single-page app or widget: the declarative mode of React Router, Wouter, or your own 80-line router.
  • An app with many screens and server data: React Router data or framework mode, or TanStack Router, so loaders, actions and pending states are not hand-wired.
  • SEO-critical, public, server-rendered content: a full-stack framework (React Router framework mode, Next.js), because a router that only runs in the browser cannot give crawlers finished HTML quickly. See Server-Side Rendering and Hydration.
  • Already inside a framework: use its router. Mixing two routers in one app is a source of subtle bugs.

Common mistakes

  • Fetching in useEffect inside every page when the router offers loaders, which creates request waterfalls.
  • Putting state that should survive a reload (filters, tabs, selected id) in useState instead of the URL.
  • Using useNavigate for plain links; use Link or NavLink.
  • Forgetting end on the root NavLink, so "Home" is always active.
  • Reading params as numbers; they are strings.
  • Not placing an errorElement near the root, so one thrown error blanks the whole app.
  • Mixing up versions: v5 Switch and component= props, v6 Routes and element=, v7 react-router. Check the version before copying a tutorial.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What problem do route loaders solve compared with fetching in useEffect inside each page component?

    An effect runs after render, so nested pages fetch one after the other. A loader runs when the navigation starts, for every matched route at once, and the component reads the finished data.
  2. 2. After a successful route action, how does React Router usually update the data on screen?

    Revalidation re-runs the loaders after an action, so lists and totals read fresh data from the source of truth. You do not update client caches by hand.
  3. 3. Two routes, /users/:id and /users/new, are both defined. Which wins for /users/new in React Router?

    Routes are ranked by specificity, so the static pattern wins regardless of order. Our mini ranker scores static segments higher than params for the same reason.
  4. 4. Where should a missing record (a valid URL like /users/99 for a user that does not exist) be reported?

    Throwing from the loader sends the router to the nearest errorElement or ErrorBoundary, where useRouteError and isRouteErrorResponse tell a 404 from a crash. The component then only handles the success case.
  5. 5. Which is the correct reason to put a filter value into the query string with useSearchParams?

    State in the URL is visible to the browser's history and to other people. Values are strings, so validate and convert them.

Summary

  • Modern routers organize an app around routes: nested route objects, ranked matching, links with active state, and navigation from code.
  • React Router has declarative, data and framework modes; TanStack Router adds end-to-end type safety; frameworks like Next.js build routing into the file system.
  • Loaders fetch data for all matched routes in parallel before render and expose it with useLoaderData; thrown errors go to the route's error element, and useNavigation reports pending states.
  • Actions handle form submissions, can return errors or a redirect, and trigger revalidation of loaders so the screen shows fresh data.
  • Framework mode generates routes from config or files, types params and loader data, and adds server rendering and per-route code splitting.
  • Keep shareable state in search params, use Link for navigation, always place error elements near the root, and check the router version before copying code.

Next: App Architecture and Project Structure