Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 50 ยท Data Mode

createBrowserRouter and RouterProvider

Enter data mode: create a router with createBrowserRouter, describe routes as objects, render it with RouterProvider, and migrate an app from BrowserRouter.

Until now, our routes were React elements: a <BrowserRouter> wrapped a <Routes> tree, and the router came to life only when React rendered it. Data mode turns that around. You build the router first, as a plain JavaScript object, outside of React. Then you hand it to React with one component, <RouterProvider>. Because the router exists before any component renders, it can do things that a component-based router cannot: start loading data for the next page the moment a link is clicked, know which forms are being submitted, and decide what to render while all of that happens.

This lesson covers the entry point of data mode: createBrowserRouter, the shape of a route object, RouterProvider, the sibling functions for memory and hash routing, and how to migrate a declarative app. The next lessons add loaders, actions and fetchers to the same routes.

From elements to route objects

A route object is the same idea as <Route>, written as data. These two definitions describe the same routes:

JSX
// Declarative mode (real React Router, read-only)
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Root />}>
      <Route index element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="products/:id" element={<Product />} />
    </Route>
  </Routes>
</BrowserRouter>
JSX
// Data mode (real React Router, read-only)
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';

const router = createBrowserRouter([
  {
    path: '/',
    Component: Root,
    children: [
      { index: true, Component: Home },
      { path: 'about', Component: About },
      { path: 'products/:id', Component: Product },
    ],
  },
]);

export default function App() {
  return <RouterProvider router={router} />;
}
flowchart LR
  R["Route objects"] --> C["createBrowserRouter(routes)"]
  H["History API<br/>pushState, popstate"] <--> C
  C --> RO["router object<br/>state, navigate, subscribe"]
  RO --> P["RouterProvider"]
  P --> T["React tree"]

The router is built outside React from route objects. RouterProvider connects the finished router to React.

Everything you learned about matching, nested routes, index routes and params works unchanged. Only the way you write the tree changes. Keep two details in mind:

  • RouterProvider comes from react-router/dom in version 7, because it needs react-dom. Everything else, including createBrowserRouter, comes from react-router.
  • Create the router once, at module level. If you call createBrowserRouter inside a component, every render builds a new router, throws away navigation state, and can loop. The router belongs outside React, like a database connection.

What a route object can contain

A route object has many optional keys. You already know the first four; the others appear in later lessons.

Key Purpose
path The URL pattern for this route, relative to its parent.
index true for an index route (no path, renders at the parent's URL).
children Nested route objects, rendered through <Outlet />.
Component or element What to render. Component takes a component type, element takes an already-created element.
loader A function that provides data before the route renders (Loaders).
action A function that handles form submissions (Actions and Form).
ErrorBoundary or errorElement What to render if a loader, action or render fails (Error Boundaries).
lazy A function that imports the route's code on demand (Lazy Routes).
handle Any value you want to attach to the route, read with useMatches (Route Handles).
shouldRevalidate Controls when the route's data reloads (Revalidation).
HydrateFallback What to show while the first loaders run. Older versions used a fallbackElement prop on RouterProvider.

Prefer Component over element in object configs. It saves you from writing JSX inside a data structure, and it is what lazy routes need. If you already have a <Routes> tree in JSX, you do not have to rewrite it: createRoutesFromElements(<Route ...>...</Route>) converts JSX routes to objects, and createBrowserRouter accepts the result.

Try it: a router that lives outside React

The stand-in below builds the same kind of object as createBrowserRouter: it takes an array of route objects and returns a router with state, navigate and subscribe. RouterProvider subscribes to it with useSyncExternalStore, the way the real one connects React to router state. Because the router is a plain object, the "Go to About" button at the bottom works from an ordinary function, with no hook at all.

Click through the pages. Watch the JSON of router.state change and notice the number of times the router has notified its subscribers.

A router object created outside React

Click "Product 7": the matchedIds array becomes ["root", "product"], the two route objects that matched, outermost first. "Broken link" matches nothing, so matchedIds is empty. The real router.state has many more fields (navigation, loaderData, actionData, errors, fetchers...), and those are exactly what the next lessons use.

Choosing the router function

createBrowserRouter is one of several creation functions. They all take the same route objects and return the same kind of router. They differ only in where the URL is stored:

JSX
// Real React Router, read-only
import {
  createBrowserRouter, // clean URLs through the History API (the default choice)
  createHashRouter,    // URLs like /#/about, no server setup needed
  createMemoryRouter,  // the location lives in memory, for tests and non-browser use
} from 'react-router';

const routes = [/* the same route objects for all three */];

const browserRouter = createBrowserRouter(routes);
const hashRouter = createHashRouter(routes);
const memoryRouter = createMemoryRouter(routes, {
  initialEntries: ['/products/7'],
});
  • createBrowserRouter is what most apps use. The server must return index.html for every path (see How Routing Works Under the Hood).
  • createHashRouter keeps the route after a #, so it works on static hosts you cannot configure, such as a plain file server. The URLs are less pretty and cannot be used for in-page anchors. It is also what our live stand-ins imitate.
  • createMemoryRouter never touches the address bar. It is the standard choice for tests, Storybook and embedded widgets. initialEntries sets the starting URLs.

All three take options as a second argument. The ones you will meet most often are basename (the app is served under a sub-path such as /app) and hydrationData (server-rendered data, covered under framework mode).

Migrating from BrowserRouter

You do not have to migrate everything at once, and you do not have to migrate at all if you only need declarative routing. When you want loaders or actions, the steps are small:

  1. Move your route definitions into an array of objects, or wrap your existing JSX with createRoutesFromElements.
  2. Call createBrowserRouter(routes) once, outside components.
  3. Replace <BrowserRouter><Routes>...</Routes></BrowserRouter> with <RouterProvider router={router} />.
  4. Move shared providers (a theme, an auth context) either above <RouterProvider>, or into a root route's component, where they can use router hooks such as useNavigate.
JSX
// Before: declarative (real React Router, read-only)
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

// After: data mode (real React Router, read-only)
const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />}>
      <Route index element={<Home />} />
      <Route path="about" element={<About />} />
    </Route>
  )
);

root.render(<RouterProvider router={router} />);

Your components keep working: Link, NavLink, useParams, useNavigate and useLocation are the same in every mode. What changes is that a few hooks now become available, and a few of them only work in a data router: useLoaderData, useActionData, useNavigation, useFetcher, useRevalidator, useRouteError and useBlocker. Calling one of them under <BrowserRouter> throws an error that says it must be used within a data router. That error is the most common sign that a migration is half finished.

Route objects in practice

Two habits make larger route files pleasant to work with.

Keep route objects close to the code they describe. A common layout is one file per feature that exports its routes, and a root file that combines them: children: [...productRoutes, ...accountRoutes]. Each feature file can import its own loader and action functions, so a route object stays a small summary of "path, data, component".

Do not put runtime logic in the route array. The array is evaluated once. If routes must depend on the signed-in user, for example hiding admin routes, keep the route list static and use guard layout routes so that decisions happen when a visitor navigates, not when the module loads.

Try it: JSX routes and object routes are the same thing

createRoutesFromElements is the bridge between the two styles. This stand-in implements it for a toy <Route> component and prints the objects it produces, so you can see that the JSX tree and the object tree are two spellings of one structure. The real function does this for every prop a route supports; the stand-in handles path, index and element.

Converting JSX routes to route objects

The page says "Yes, identical": the JSX you write in declarative mode and the objects you write in data mode become the same tree. That is why you can move between the two styles whenever you like.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you call createBrowserRouter?

    The router holds navigation state and must exist for the lifetime of the app. Creating it inside a component builds a new router on each render and loses that state.
  2. 2. Which of these hooks only works inside a data router?

    useParams, useNavigate and useLocation work in every mode. Loader data, action data, navigation state, fetchers, revalidation, route errors and blockers need a data router.
  3. 3. You need a router for a unit test that should not touch the address bar. Which function fits?

    createMemoryRouter keeps the location in memory and takes initialEntries as the starting URLs, which makes tests independent of the browser's URL.
  4. 4. What does RouterProvider do?

    The router is built first from route objects. RouterProvider takes it as a prop, subscribes to its state and renders the matching routes.

Summary

  • Data mode builds the router first with createBrowserRouter(routes), then renders it with <RouterProvider router={router} /> (imported from react-router/dom).
  • A route object is <Route> written as data: path, index, children, Component, plus keys such as loader, action, ErrorBoundary, lazy and handle.
  • Create the router once at module level, never inside a component.
  • createHashRouter and createMemoryRouter take the same routes and differ only in where the URL is stored.
  • To migrate, convert or wrap your routes, swap BrowserRouter for RouterProvider, and remember that several hooks work only in a data router.
  • The live examples use a stand-in with the same shape: route objects in, a router with state, navigate and subscribe out.

Next: Loaders: Data Before Render