Sub topic 2
Setting up the router
This chapter shows how to install React Router, create a router object, and mount it in your app. It assumes you know ES modules, React function components, and JSX. It also assumes you have a React app running, for example one created with Vite. The chapter ends with the mistakes that most often break a first setup.
What setup involves
React Router's data router API splits the setup into two steps:
- Describe your routes as plain JavaScript objects and pass them to
createBrowserRouter. This returns a router object. - Pass that router object to the
RouterProvidercomponent, which renders whatever the current URL matches.
The router object owns the navigation state: the current location, the matched routes, any loader data, and whether a navigation is in progress. React components only read that state. This is why loaders, actions, and pending UI, which later chapters cover, all depend on this setup.
Installing
Install the package with your package manager:
npm install react-router-domThis tutorial imports from react-router-dom, as the examples do throughout. Version 6.4 or later is required for the data router functions. In React Router v7 the same APIs are exported from react-router, and react-router-dom re-exports them. The code in this chapter works with either package once the import path matches what you installed.
The smallest working router
Put the router in its own module-level constant, then render it with RouterProvider.
// src/main.jsx
import React from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
function Home() {
return <h1>Home</h1>;
}
function About() {
return <h1>About</h1>;
}
const router = createBrowserRouter([
{ path: "/", element: <Home /> },
{ path: "/about", element: <About /> },
]);
createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);Open / and you see "Home". Open /about and you see "About". Typing either URL directly in the address bar works in the Vite dev server, because it serves index.html for unknown paths.
createBrowserRouter takes two arguments:
- An array of route objects. Each object needs a
path(orindex: true, covered in a later chapter) and something to render, usuallyelement. - An optional options object. The ones you will use most are
basenameandinitialEntries(memory routers only).
What happens on navigation
The browser router uses the History API. When the user clicks a link, the router updates the URL with history.pushState and does not request a new page from the server. It then matches the new URL against your route objects and re-renders.
The back and forward buttons enter the same flow at the matching step, so they behave the same as clicking a link.
Why create the router outside components
The router holds state that must survive re-renders. If you call createBrowserRouter inside a component body, every render builds a new router. The app then loses its navigation state and may remount the whole tree.
// Wrong: a new router is created on every render of App
function App() {
const router = createBrowserRouter([{ path: "/", element: <Home /> }]);
return <RouterProvider router={router} />;
}Create the router once at module scope, as in the earlier example. If the route list is long, move it to its own file, such as src/router.jsx, and export the router from there.
// src/router.jsx
import { createBrowserRouter } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
export const router = createBrowserRouter([
{ path: "/", element: <Home /> },
{ path: "/about", element: <About /> },
]);// src/App.jsx
import { RouterProvider } from "react-router-dom";
import { router } from "./router";
export default function App() {
return <RouterProvider router={router} />;
}Adding a layout from the start
Most apps share a header or navigation bar across pages. You can set this up at the start with a layout route. It is a route with children, and its element renders an Outlet where the matched child appears. Later chapters cover nesting in detail. This is the minimal version:
import { createBrowserRouter, RouterProvider, Link, Outlet } from "react-router-dom";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</nav>
<Outlet />
</div>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "about", element: <h1>About</h1> },
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}The Link components work here because they render inside RouterProvider. Cl changes the URL and swaps the child in the Outlet. The Layout stays mounted, so its state is preserved.
Data router versus the older component API
Older React Router tutorials use <BrowserRouter> with <Routes> and <Route>. That API still works, but it has no loaders, actions, errorElement, or navigation state. Those features need a data router, which is what createBrowserRouter creates.
| Feature | `BrowserRouter` + `Routes` | `createBrowserRouter` + `RouterProvider` |
|---|---|---|
| Routes defined as | JSX elements | Plain objects |
| Loaders and actions | No | Yes |
| `errorElement` | No | Yes |
| `useNavigation` | No | Yes |
| Router created | In render | Once, outside React |
Do not mix the two in one tree. Pick the data router for new code.
Production hosting and deep links
A single-page app serves one HTML file, but users can open /about directly or reload on it. The dev server handles this for you. A production static host must be configured to return index.html for any path that is not a real file. Without that, a reload on /about returns the host's 404 page, because the server has no about file.
For nginx, the rule is:
location / {
try_files $uri /index.html;
}Most managed static hosts have an equivalent setting, often called a rewrite or SPA fallback.
If the app is served from a sub-path, such as https://example.com/app/, set basename. Route paths then stay written relative to the app root:
const router = createBrowserRouter(
[{ path: "/", element: <h1>Home</h1> }],
{ basename: "/app" }
);With this, the route / matches the URL /app/, and a <Link to="/about"> renders an href of /app/about.
Common errors
- "useRoutes() may be used only in the context of a Router" or a similar message. A component that uses
Linkor a router hook is rendering outsideRouterProvider. Check that the component is in the tree under the provider. This also happens in tests that render a component without a router. - Blank page and no error. The route's
elementis missing, or the URL matches nothing and you have noerrorElementor catch-all route. React Router shows a default 404 screen in development when no route matches. A fully blank page usually means a route matched but itselementisundefined. - Passing a component instead of an element. Write
element: <Home />, notelement: Home. The first is a React element. The second is a function, and React Router will not render it. - Reload gives a 404 in production only. The host is missing the
index.htmlfallback described above. - Router recreated on every render. See the section on module-level creation. Symptoms include state resetting on each navigation.
- Loaders ignored. You defined a
loaderbut used<BrowserRouter>. Switch tocreateBrowserRouter.
Summary
You install react-router-dom, describe routes as objects, create the router once at module scope with createBrowserRouter, and render it with RouterProvider. This data router enables loaders, actions, error elements, and navigation state. For production, configure the host to fall back to index.html, and set basename if the app lives under a sub-path.
Exercise
A teammate writes function App() { const router = createBrowserRouter(routes); return <RouterProvider router={router} />; }. The app works at first, but a counter in the page layout resets to zero whenever state in App changes. What is wrong, and how do you fix it?
Show answer
createBrowserRouter runs on every render of App, so each render builds a new router and the tree below it loses its state. Move the createBrowserRouter(routes) call to module scope, outside App, and keep only <RouterProvider router={router} /> inside the component.
Exercise
Your app works locally at /about. After deploying to a static host, clicking the About link works, but reloading on /about shows the host's 404 page. Why does this happen, and what do you change?
Show answer
Clicking the link uses pushState, so the browser never asks the server for /about. A reload sends a real request for /about, and the host has no such file. Configure the host to return index.html for paths that are not files (for nginx, try_files $uri /index.html;). The router then loads and matches /about in the browser.