Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 50 ยท Declarative Routing Basics

Routes as Objects: useRoutes and Route Configs

Describe React Router routes as plain objects with useRoutes or createRoutesFromElements, compare them with JSX, and share one route config across router modes.

So far routes have been written as JSX: <Route path="about" element={<About />} />. That reads nicely, but it hides something important. A route is just data: a path, something to render and perhaps some children. React Router turns your <Route> elements into plain JavaScript objects before it matches anything. You can skip the JSX and write those objects yourself.

Why bother? An object config can be built from other data, split across files, filtered by user role, inspected in tests and reused by every kind of router React Router offers (declarative, data and framework mode share the same ideas). In this lesson you will learn the two APIs that work with objects, useRoutes and createRoutesFromElements, see what a route object may contain, and run a small matcher over an array of route objects.

JSX routes and what they become

This is the usual declarative-mode code (real React Router, read-only):

JSX
// App.jsx - React Router (read-only)
import { BrowserRouter, Routes, Route } from 'react-router';

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

<Route> never renders anything on its own. It is only a way to write down configuration, and <Routes> reads its children's props. Internally it does two steps: convert the elements to route objects, then hand the objects to the matcher that useRoutes uses. The next example makes that conversion visible with a hand-written stand-in.

Real library or stand-in? The live examples use a small hand-written router built on React and location.hash, because the sandboxed editor cannot install packages. The stand-in's routesFromElements imitates createRoutesFromElements, and its useRoutes imitates the real hook, but they are far simpler (no ranking, no case sensitivity, no error handling). The real code is always shown in read-only blocks.

JSX routes and route objects are the same data

The printed structure is the whole idea: a tree of { path, element, children } objects, with index: true marking the default child. The comparison at the bottom prints true, so for this tree the JSX version and the object version carry exactly the same information.

useRoutes: the hook behind Routes

useRoutes(routes) takes an array of route objects and returns the element to render (or null when nothing matches). It must be called inside a router such as BrowserRouter:

JSX
// AppRoutes.jsx - React Router (read-only)
import { BrowserRouter, useRoutes, Outlet } from 'react-router';

function AppRoutes() {
  return useRoutes([
    {
      path: '/',
      element: <Layout />,
      children: [
        { index: true, element: <Home /> },
        { path: 'about', element: <About /> },
        { path: '*', element: <NotFound /> },
      ],
    },
  ]);
}

export default function App() {
  return (
    <BrowserRouter>
      <AppRoutes />
    </BrowserRouter>
  );
}

<Routes> is essentially useRoutes(createRoutesFromChildren(children)) wrapped in a component, so the two styles are interchangeable. Pick the object style when your routes come from somewhere else: a list per feature, a permissions table or generated code. A second reason is that the same array can be passed to other APIs, which is the next section.

What a route object can contain

Field Meaning
path A pattern relative to the parent, such as about, users/:id or *. Omit it for a layout or index route.
index true marks the default child of the parent. An index route has no path and no children.
element A React element to render, for example <Home />.
Component A component to render instead of an element. React Router creates the element for you, which is handy with lazy loading.
children An array of nested route objects. The parent renders them through Outlet.
caseSensitive Makes matching of this route's path case-sensitive (off by default).
id A unique name. Data routers and useMatches use it.
loader, action, errorElement, lazy, ... Data-mode fields. They only work when the routes are given to a data router; useRoutes inside BrowserRouter ignores them.

The last row is the main reason to prefer objects in a growing app: the day you want loaders and actions, you do not rewrite your routes, you pass the same array to a different function.

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

// Production: URLs in the address bar.
export const router = createBrowserRouter(routes);

// Tests: the same routes with an in-memory history.
export const testRouter = createMemoryRouter(routes, { initialEntries: ['/about'] });

// <RouterProvider router={router} />

If you still prefer to write JSX, createRoutesFromElements converts it for a data router:

JSX
// router.jsx - React Router (read-only)
import { createBrowserRouter, createRoutesFromElements, Route } from 'react-router';

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<Layout />}>
      <Route index element={<Home />} />
      <Route path="about" element={<About />} />
    </Route>
  )
);
flowchart LR
    A["JSX: Routes and Route"] --> C["Array of route objects"]
    B["Objects written by hand<br/>or generated"] --> C
    C --> D["useRoutes in BrowserRouter"]
    C --> E["createBrowserRouter<br/>(data mode)"]
    C --> F["createMemoryRouter<br/>(tests)"]
    D --> G["matches, then rendered tree"]
    E --> G
    F --> G

Every style ends as the same array of route objects. The object form simply lets you skip the JSX step.

Matching over an array

What does a router do with that array? It walks the tree, compares each route's path with the next segments of the URL, and returns a list of matches from the outermost route to the innermost. React Router exposes this as matchRoutes(routes, location), which returns objects shaped like { params, pathname, pathnameBase, route }. The stand-in below returns a simpler { route, params } and shows the chain for several URLs. It uses id fields so the output is readable.

Matching URLs against route objects

Read the chains left to right: /users/42 matches root, then users, then user-detail, and the param userId is "42". /users/42/photos has no route for photos, so the walk falls out of users and ends in the catch-all (not-found). The last row repeats the current hash, so clicking the links shows live matches.

Routes built from data

Because the config is an array, you can assemble it. A common pattern is one routes module per feature, joined at the top, or a function that includes some routes only for certain users.

A route config built from feature modules

Open "Admin" with the toggle off: the route does not exist, so you get the 404. Switch it on and the same link works. This shows why configs as data are powerful, but also a limit: leaving a route out only hides it in the browser. Anyone can read your bundle, and the server must still check permissions. Protected Routes and Auth Redirects covers the proper pattern.

Which style should you use?

  • JSX routes are great for small apps and when the tree should read like the UI tree.
  • Objects are better for medium and large apps, for generated routes, and when you may adopt data mode. They also make it easy to unit-test the configuration.
  • Mixing is fine: createRoutesFromElements gives you objects from JSX at any time.
  • Keep the config in its own module (routes.jsx) so that the router, tests and breadcrumb code can import it. The route handles lesson builds on that.

For the upgrade story between modes, see Choosing Between Declarative, Data and Framework Mode. The routing basics also appear in a from-scratch form in Client-Side Routing and the overview in React Router and Framework Routers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does <Routes> do with its <Route> children?

    A <Route> renders nothing by itself. <Routes> converts the elements into route objects (like createRoutesFromChildren) and passes them to the same matching code that useRoutes uses.
  2. 2. You pass the same array of route objects to createBrowserRouter instead of useRoutes. What is the main benefit?

    Route objects are the common format. Data-mode fields such as loader, action and errorElement are honored by data routers; a plain useRoutes inside BrowserRouter ignores them.
  3. 3. Which route object is an index route?

    An index route is marked with index: true. It has no path of its own and renders in the parent's Outlet when the parent's URL matches exactly.
  4. 4. Your app leaves the /admin route out of the config for normal users. Is that enough to secure the admin area?

    Client code is visible and can be changed by the user. Hiding routes is a user-interface convenience; real protection must come from the server checking each request.

Summary

  • A route is data: path, element (or Component), children and index, plus data-mode fields such as loader and action.
  • JSX <Route> elements are only a way to write that data; createRoutesFromElements turns them into objects.
  • useRoutes(routes) renders an object config inside a router, and <Routes> is the JSX version of the same thing.
  • The same array works with createBrowserRouter, createMemoryRouter and matchRoutes, so object configs are the easiest to grow into data mode and to test.
  • Configs can be assembled from feature modules or filtered by role, but filtering routes in the browser is not security.

Next: Redirects with Navigate