Lesson 6 of 11 · 12 min · Building apps

Routing with React Router

Covers: React 19 with React Router 7 and TypeScript. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • What client-side routing is and why single-page apps need it
  • Define routes with createBrowserRouter and RouterProvider
  • Navigate with Link, NavLink and useNavigate
  • Nested routes, layouts and Outlet
  • Read URL parameters and search params; protect routes; handle 404s

In simple words

In a traditional website, every link asks the server for a whole new page. A single-page app loads once and then swaps parts of the screen itself while updating the address bar, so moving around feels instant. A router is the part of the app that watches the address, decides which component to show for it, and makes links and the back button work like a normal website.

Words to know

  • Route: a rule that matches a URL path to a component.
  • Single-page app (SPA): an app that loads one HTML page and updates the screen with JavaScript.
  • URL parameter: a variable part of the path, such as the 5 in /orders/5.
  • Outlet: the place in a layout where the matching child route is shown.

Why a router

  • The address should reflect where the user is, so links can be bookmarked and shared, and back and forward work.
  • Pages are components; the router chooses which to render for the current URL.
  • Navigation does not reload the page: state and scroll can be kept, and transitions are fast.

React itself has no router; React Router is the most widely used (TanStack Router and Next.js's file-based router are other options). React Router 7 (2024 and later) merges the older React Router and Remix; you can use it as a library (declarative or data mode, as below) or as a full framework with server rendering. Import from react-router (the react-router-dom package still re-exports it).

npm install react-router

Defining routes (data mode)

// src/main.tsx
import { createBrowserRouter, RouterProvider } from "react-router";
import { createRoot } from "react-dom/client";
import Layout from "./Layout";
import Home from "./pages/Home";
import Courses from "./pages/Courses";
import CourseDetail from "./pages/CourseDetail";
import NotFound from "./pages/NotFound";

const router = createBrowserRouter([
  {
    path: "/",
    Component: Layout,                       // shared layout with an <Outlet />
    children: [
      { index: true, Component: Home },      // "/"
      { path: "courses", Component: Courses },            // "/courses"
      { path: "courses/:courseId", Component: CourseDetail },   // "/courses/42"
      { path: "*", Component: NotFound },    // anything else
    ],
  },
]);

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

Elements of a route: path (relative to the parent, with :param for variables, * for a catch-all), index (the default child), Component or element, children, plus loader, action and errorElement/ErrorBoundary (below).

Layouts and Outlet

A layout renders shared UI (header, sidebar, footer) and an <Outlet /> where the matching child appears:

// Layout.tsx
import { NavLink, Outlet } from "react-router";

export default function Layout() {
  return (
    <>
      <header>
        <nav aria-label="Main">
          <NavLink to="/" end>Home</NavLink>
          <NavLink to="/courses">Courses</NavLink>
        </nav>
      </header>
      <main>
        <Outlet />
      </main>
      <footer>© Example</footer>
    </>
  );
}

Routes nest: courses can have its own children (courses/:id/lessons) rendered into an <Outlet /> inside Courses. Route files that share a layout keep their header and state while only the inner part changes.

URL parameters and search params

import { useParams, useSearchParams } from "react-router";

function CourseDetail() {
  const { courseId } = useParams();                    // string | undefined: "42"
  const id = Number(courseId);
  // ...
}

function Courses() {
  const [searchParams, setSearchParams] = useSearchParams();
  const level = searchParams.get("level") ?? "all";
  const page = Number(searchParams.get("page") ?? 1);

  return (
    <>
      <select
        value={level}
        onChange={(e) => setSearchParams({ level: e.target.value, page: "1" })}
      >
        <option value="all">All</option>
        <option value="beginner">Beginner</option>
      </select>
      {/* render the filtered list for `level` and `page` */}
    </>
  );
}

Params are always strings: convert and validate them. Keep shareable state in the URL: filters, sort, page, selected tab and search text belong in the search params, so a reloaded or shared link shows the same view, rather than in component state that disappears.

Loaders and actions (data mode)

React Router can load data before rendering a route, avoiding "empty page then spinner" flicker and request waterfalls:

{
  path: "courses/:courseId",
  loader: async ({ params, request }) => {
    const response = await fetch(`/api/courses/${params.courseId}`, { signal: request.signal });
    if (response.status === 404) throw new Response("Not found", { status: 404 });
    return response.json();
  },
  Component: CourseDetail,
  ErrorBoundary: RouteError,
}

import { useLoaderData, useRouteError, isRouteErrorResponse } from "react-router";

function CourseDetail() {
  const course = useLoaderData() as Course;
  return <h1>{course.title}</h1>;
}

function RouteError() {
  const error = useRouteError();
  return isRouteErrorResponse(error)
    ? <p>{error.status === 404 ? "Course not found." : "Something went wrong."}</p>
    : <p>Unexpected error.</p>;
}

Actions handle form submissions (<Form method="post">) and revalidate loaders afterwards. You can also keep fetching inside components with TanStack Query (the next lesson) and use the router only for URLs; both are valid. In framework mode, routes are files, with server rendering, loaders on the server and type-safe route modules.

Protected routes

Send signed-out users to the login page, and return them afterwards:

import { Navigate, Outlet, useLocation } from "react-router";

function RequireAuth() {
  const { user } = useAuth();
  const location = useLocation();
  if (!user) return <Navigate to="/login" replace state={{ from: location }} />;
  return <Outlet />;
}

// in the route tree
{ Component: RequireAuth, children: [{ path: "account", Component: Account }] }

Remember: client-side route protection is a user-experience feature only. Anyone can read your JavaScript bundle, so the server (API) must enforce authentication and authorisation for every request.

404 pages, redirects and scroll

  • A path: "*" route renders your Not Found page; also return a real 404 status from the server for unknown URLs when you can (important for SEO and for monitoring).
  • redirect("/new-path") in loaders, <Navigate>, or a server redirect for moved URLs.
  • Set a document title per route (<title> in React 19 can be rendered from any component and is hoisted to <head>).
  • Scroll restoration (<ScrollRestoration />) and focus management after navigation matter for accessibility: in an SPA the browser does not announce a page change, so move focus to the new page's <h1> or announce it in a live region.
  • Lazy-load route code: { path: "reports", lazy: () => import("./pages/Reports") } so each page's JavaScript downloads only when visited.

Server configuration for SPAs

When someone opens https://example.com/courses/42 directly, the server receives that path. For a client-routed SPA, configure the server (Nginx, a CDN, Netlify, Vercel) to return index.html for unknown paths, so React Router can take over:

location / { try_files $uri /index.html; }

Vite's dev server already does this.

Common mistakes

  • Using <a href> for internal links (reloads the page and loses state); use <Link>.
  • Forgetting end on the Home NavLink so it is always active.
  • Treating params as numbers without converting and validating.
  • Storing filter and page state in component state instead of the URL.
  • Thinking a protected route is secure without server checks.
  • Not configuring the server fallback (404 on refresh).
  • No 404 route or no focus handling on navigation.

Try it yourself

  1. Create a Vite React app and add routes for Home, Courses, a course detail page and a 404 page, with a shared layout and NavLinks.
  2. Make the courses list read ?level= and ?page= from the URL and update them with setSearchParams.
  3. Add a loader to the detail route and an error element for 404 and server errors.
  4. Add a protected route that redirects to /login and returns afterwards.
  5. Refresh a deep link in production mode (npm run build && npm run preview) and in a server without a fallback to see the 404.

Check yourself

What is client-side routing?

Changing the visible components and URL with JavaScript, without requesting a new HTML page from the server, so navigation is fast and keeps app state.

What does <Outlet /> do?

It marks where the matched child route is rendered inside a parent layout.

Where should filters, sort order and page number be kept?

In the URL's search params, so they survive reloads, can be bookmarked and shared, and work with the back button.

Why is a client-side protected route not real security?

The browser code is visible and modifiable; the API must verify authentication and permissions on every request.

Interview questions

How does React Router work?

It reads the browser URL (using the History API), matches it against route definitions, renders the matching component tree with layouts and outlets, and handles link clicks and the back button without reloading the page.

How do you pass data between routes?

Through URL params and search params, Link or navigate state, shared context or a store, or by loading the data in the target route's loader.

What is the difference between Link and NavLink?

Link navigates; NavLink additionally knows whether its target matches the current URL and exposes isActive and aria-current for styling the active link.

Summary

  • A router maps URLs to components and handles links, history and layouts without page reloads.
  • Define routes with createBrowserRouter; use Link, NavLink, Outlet, useParams and useSearchParams.
  • Keep shareable state in the URL; load data in loaders or with a data library; handle 404 and errors.
  • Client-side guards are only UX; secure the API and configure the server to serve index.html for deep links.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.