Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 50 ยท Production Concerns

Route Handles and Breadcrumbs

Attach metadata to routes with the handle property, read the whole match chain with useMatches, and build breadcrumbs, page titles and layout switches from it.

Most apps need information that belongs to a route but is not rendered by it: a breadcrumb label, a page title, a flag that says "hide the sidebar here". The layout that needs this information sits above the page in the component tree, so the page cannot simply pass it down. The layout has to ask the router instead: "which routes are matched right now, and what do they say about themselves?"

React Router answers with two small pieces. A route can carry a handle, an arbitrary value you attach to the route object, and the hook useMatches() returns the chain of matched routes, each with its handle. In this lesson you will use them to build a breadcrumb trail, a document title and a layout switch. You will need the ideas from Nested Routes and Outlet and Loaders: Data Before Render.

What handle and useMatches are

handle is a property of a route object in data mode (and an export of a route module in framework mode). React Router never reads it and never changes it. It is a labelled shelf where you put whatever your app wants to find later.

useMatches() returns an array with one entry per matched route, from the outermost route to the innermost. Every entry is an object with these fields:

  • id: the route's unique id.
  • pathname: the URL path that route matched (so a link to it is just <Link to={match.pathname}>).
  • params: the dynamic segments known at that level.
  • data: what that route's loader returned (undefined if it has none).
  • handle: the route's handle value.

Here is the real React Router code. It is read-only because the live editor cannot install packages:

JSX
// routes.jsx - React Router (read-only)
import { createBrowserRouter, Outlet, Link, useMatches } from 'react-router';

const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    handle: { crumb: () => 'Home' },
    children: [
      { index: true, element: <Welcome /> },
      {
        path: 'courses',
        handle: { crumb: () => 'Courses' },
        children: [
          { index: true, element: <CourseList /> },
          {
            path: ':slug',
            loader: courseLoader,
            element: <Course />,
            handle: { crumb: (data) => data.title },
          },
        ],
      },
    ],
  },
]);

function Breadcrumbs() {
  const matches = useMatches();
  const crumbs = matches.filter((match) => match.handle?.crumb);

  return (
    <nav aria-label="Breadcrumb">
      <ol>
        {crumbs.map((match, index) => (
          <li key={match.id}>
            {index < crumbs.length - 1 ? (
              <Link to={match.pathname}>{match.handle.crumb(match.data)}</Link>
            ) : (
              <span aria-current="page">{match.handle.crumb(match.data)}</span>
            )}
          </li>
        ))}
      </ol>
    </nav>
  );
}

Three details are worth pausing on:

  1. Index routes are matches too. For /courses the array holds the root route, the courses route and the index route inside it. That is why the code filters for entries that actually have a crumb: the index route has no handle, so it is skipped.
  2. A crumb can be a function. The handle is plain data, so it can hold a string, a function or even a React element. A function is the most flexible: it receives the loader data, so the label can be the real course title instead of the slug in the URL.
  3. useMatches needs a data router. It works with createBrowserRouter and RouterProvider (and in framework mode), not with the older <BrowserRouter> setup of Installing and Your First Routes. The data-router setup is covered in createBrowserRouter and RouterProvider.
flowchart LR
    A["URL: /courses/react"] --> B["Matched routes<br/>root, courses, :slug"]
    B --> C["useMatches()<br/>array of match objects"]
    C --> D["filter: has handle.crumb"]
    D --> E["Home / Courses / React Basics"]

The router builds the chain; your layout filters it and turns the handles into UI.

Real library or stand-in? The code above is the real API. The live examples below use a small hand-written router built on React and location.hash. It resolves nested routes, collects the matches (each with pathname, params, data and handle) and exposes them through a useMatches() of its own. In the stand-in, loaders are plain synchronous functions run during rendering, while the real router runs async loaders before it renders. The matching idea is explained in Client-Side Routing.

Building a breadcrumb trail

Run the example and click through the links. Under the breadcrumb, a small panel prints exactly what useMatches() returned, so you can see the index route appear and disappear.

Breadcrumbs from route handles

Open "SQL" and compare the trail ("Home / Courses / SQL Joins") with the panel: three matched routes, three crumbs. Then open "Courses": the panel now shows the index route too, but the trail has only two crumbs because the index route has no handle. A trail made this way is declarative: to add a level, you add a route with a handle. No page component knows it appears in a breadcrumb.

Crumbs that use loader data

URL segments are rarely good labels. The slug react is fine, but /orders/8f3a should read "Order #1042". Because each match carries the data its loader returned, the crumb function can use it. The same trick gives you a page title, and a layout can read flags such as "this page is a focused view".

JSX
// routes.jsx - React Router (read-only)
{
  path: ':slug',
  loader: courseLoader,
  element: <Course />,
  handle: {
    crumb: (data) => data.title,
    title: (data) => `${data.title} | Courses`,
  },
  children: [
    {
      path: 'lessons/:n',
      loader: lessonLoader,
      element: <Lesson />,
      handle: { crumb: (data) => data.title, focus: true },
    },
  ],
}

The layout combines the matches into three results: breadcrumbs, a title and a layout switch.

JSX
// Layout.jsx - React Router (read-only)
function Layout() {
  const matches = useMatches();
  const lastTitle = matches.findLast((match) => match.handle?.title);
  const focused = matches.some((match) => match.handle?.focus);

  useEffect(() => {
    document.title = lastTitle ? lastTitle.handle.title(lastTitle.data) : 'Academy';
  }, [lastTitle]);

  return (
    <>
      <Breadcrumbs />
      {!focused && <CourseSidebar />}
      <Outlet />
    </>
  );
}

The title and focus handling here is deliberately small. Scroll Restoration, Focus and Page Titles covers announcing page changes to screen readers, which a changing title alone does not do.

Titles, crumbs and a focus switch from handles

Start at "React" and open a lesson link: the trail grows by one crumb, the tab title is taken from the innermost route that defines one, and the menu disappears because the lesson route set focus: true. None of the three components that react to this (breadcrumbs, title, menu) were told which page you are on; they only read the matches.

Practical notes

  • Keep handles small and serializable in spirit. Labels, flags and functions are fine. Do not put big objects or anything that must stay in sync with state there: a handle is created once, with the route.
  • Type it yourself. handle is typed as unknown. Write one RouteHandle type and a small type guard (hasCrumb(match)) so your layout does not scatter casts around.
  • Filter, do not assume. Never read matches.at(-1).handle blindly. The innermost match is often an index route without a handle, and the nearest handle may belong to a parent.
  • Decide on an order. For breadcrumbs you walk the array outer to inner. For a title or a flag you usually want the innermost route that defines it (findLast).
  • Use real links. Breadcrumb entries are links to match.pathname, so they work with keyboard and screen readers, and the last entry is plain text marked with aria-current="page".
  • Search engines read breadcrumbs better if you also emit BreadcrumbList structured data from the same array, which only matters when the pages are server rendered (see SSR, Streaming and Deployment).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does React Router do with a route's handle value?

    handle is an opaque shelf for your own metadata. The router never interprets it; you read it from the entries returned by useMatches().
  2. 2. For the URL /courses, the matched routes are root, courses and an index route inside courses. Why does a breadcrumb component filter the matches before rendering?

    Index routes and other routes without a crumb are part of the chain but contribute nothing to the trail, so you keep only the matches whose handle defines a crumb.
  3. 3. A crumb should show the title of the current course instead of the slug in the URL. What makes this possible?

    useMatches() returns each route's loader data in the data field, so handle.crumb(data) can build a label from it.
  4. 4. Which setup does useMatches() need?

    The hook relies on the route objects and match data managed by a data router, so it is available in data mode and framework mode.

Summary

  • handle is a free-form property on a route; the router stores it and never reads it.
  • useMatches() returns the matched routes from outermost to innermost, each with id, pathname, params, data and handle.
  • Breadcrumbs are the matches that define a crumb, linked to match.pathname, with the last one as plain text and aria-current="page".
  • Crumb and title functions can use loader data, so labels come from real records instead of URL segments.
  • The same pattern drives page titles and layout switches; take the innermost value with findLast.
  • It needs a data router or framework mode, and handle is typed unknown, so add your own type and guard.

Next: Modal Routes and Background Locations