React Router Data Router: The URL as the Place for State
The data router in React Router makes the URL the point of coordination – a route loads its data via loader before rendering and writes via action, so loading logic disappears from the component body.
React Router Data Router: The URL as the Place for State
In the data router of React Router, a route is no longer a mapping from path to component. It is a complete description of everything that belongs to an address: which part of the UI appears, where its data comes from, what happens on a write, what you see when something fails. These descriptions are objects, and because they exist before the first render, the router can read from them what to do for a URL – without running a single component.
How far this goes becomes clear when you compare it with the pattern the classic approach suggests: a route renders a component, the component has a useEffect, the effect loads the data, and next to it sit three useState calls for loading state, error and result. For one page, that works. For twenty nested pages, you get loading waterfalls: the outer component renders, its effect loads, only then does the inner one render, and its effect loads – one after the other, even though both were known from the start. In the React overview, I still showed routing with BrowserRouter and Routes and deliberately left the modern approach aside; it is the subject of this post. The data router reverses the order.
Editorial note (July 2026): React Router 8 distinguishes three modes: Declarative, Data and Framework. This post covers Data Mode with createBrowserRouter. Framework Mode builds on it and adds, among other things, typed route modules, code splitting and optional SPA, SSR and static rendering strategies.
The core idea: the route loads before it renders#
The key difference fits into one sentence. With the old approach, the component renders first and then loads its data. With the data router, the route loads its data first and then renders the component – with the data already in hand. For this, every route gets a function, the loader. It runs during navigation, before anything appears on the screen. Only when it’s done does React render the component, which picks up the data fully loaded instead of fetching it itself.
This removes the loading logic from the component body. No more useEffect that loads on first render, no handful of useState calls for a state that, strictly speaking, should never exist – because by the time the component renders, the data is long there. The writing counterpart is called action. It receives form submissions, writes to the server, and afterward React Router reloads the affected loaders on its own so that the view is correct again.
createBrowserRouter and the route objects#
You no longer describe the application as nested JSX elements but as objects. createBrowserRouter takes an array of route definitions, and each definition carries its building blocks in one place: the path, the component, the loader, the action, the error element.
import { createBrowserRouter } from "react-router";
import { RouterProvider } from "react-router/dom";
const router = createBrowserRouter([
{
path: "/invoices",
element: <InvoiceList />,
loader: invoiceListLoader,
errorElement: <RouteError />,
children: [
{
path: ":invoiceId",
element: <InvoiceDetail />,
loader: invoiceDetailLoader,
action: invoiceDetailAction,
},
],
},
]);
function App() {
return <RouterProvider router={router} />;
}
Instead of hunting for path and element scattered across half the application, everything that makes up a route sits together: what it shows, where its data comes from, how it responds to writes, what happens on an error. This bundling is not a cosmetic advantage. It is the prerequisite for React Router knowing the data before rendering – because the router can read from the object tree which loaders are responsible for a URL without rendering the components first.
The loader: fetch data before rendering#
A loader is an ordinary function. Among other things, it receives the parameters from the path, fetches the data and returns it. In the component, you pick it up with useLoaderData().
import { useLoaderData } from "react-router";
async function invoiceDetailLoader({ params }) {
const response = await fetch(`/api/invoices/${params.invoiceId}`);
if (!response.ok) {
throw new Response("Not found", { status: 404 });
}
return response.json();
}
function InvoiceDetail() {
const invoice = useLoaderData();
return <h1>Invoice {invoice.number}</h1>;
}
Note what isn’t here. No useState for the invoice, no useEffect for loading, no check for null while loading is still in progress. When InvoiceDetail renders, the loader has finished. Whether invoice exists in domain terms is something the loader itself has to guarantee – for example by throwing a 404 response on an empty result. The router’s waiting doesn’t replace this validation.
The real gain shows with nested routes. If someone opens /invoices/42, two routes are involved: the list and the detail. With the useEffect approach, this would run sequentially – first the list renders and loads, then the detail renders and loads. React Router knows both loaders in advance and starts them in parallel. That eliminates the waterfall: all affected loaders start at the same time, and the page is ready as soon as the slowest one is through.
flowchart TB Nav["Navigation to /invoices/42"] Nav --> Match["Router determines affected routes"] Match --> L1["loader list"] Match --> L2["loader detail"] L1 --> Ready["all loaders done"] L2 --> Ready Ready --> Render["Components render<br/>with useLoaderData"]
Here the connection to the server cache is worth making. In the post on client state and server cache, I showed that server data is not state you own but a copy you manage – with a key, an age and invalidation, which is what a library like TanStack Query is good for. The loader sits one level above that. It says when to load, namely during navigation, tied to the route instead of the component. Whether there’s a bare fetch or a cache behind it is unaffected. The two complement each other cleanly: the loader calls the queryClient, and the library decides whether it holds a fresh copy or really reloads. The router determines the timing, the cache the validity – they don’t exclude each other, they mesh.
The action: writing via <Form>#
For writes, React Router provides its own component. <Form method="post"> looks like an ordinary HTML form but is intercepted by the router: instead of reloading the page, it calls the action of the matching route and passes it the form data.
import { Form, redirect } from "react-router";
async function invoiceDetailAction({ request, params }) {
const formData = await request.formData();
await fetch(`/api/invoices/${params.invoiceId}/pay`, {
method: "POST",
body: formData,
});
return redirect(`/invoices/${params.invoiceId}`);
}
function InvoiceDetail() {
const invoice = useLoaderData();
return (
<Form method="post">
<button type="submit">Mark as paid</button>
</Form>
);
}
The decisive part happens after the action: by default, React Router revalidates the loaders of the active routes. The invoice has been paid, the action is through, and the view can show the fresh state because the affected loaders ran again. You can restrict this behavior with shouldRevalidate; external caches still have to be invalidated appropriately. The flow resembles the browser principle of “submit the form, fetch the page again,” just without rebuilding the whole document.
flowchart LR F["Form method=post"] --> A["action writes<br/>to the server"] A --> R["loaders are<br/>revalidated"] R --> U["View shows<br/>fresh state"]
If you compare this with the useEffect dashboard from the server cache post, you’ll recognize the same illness and a different medicine. There, the number at the top and the list next to it drifted apart because nobody made sure both reloaded after paying. Here, they reload together after the action, because revalidation affects all loaders of the active route levels and not a single component.
Nested routes and <Outlet />#
The objects from the first example had children, and that’s more than a matter of organization. Nested routes mirror the UI hierarchy: an outer layout route renders the frame – navigation, header, sidebar – and where the inner route should appear, it places an <Outlet />.
import { Outlet, NavLink } from "react-router";
function InvoiceList() {
const invoices = useLoaderData();
return (
<div className="layout">
<nav>
{invoices.map((invoice) => (
<NavLink key={invoice.id} to={`/invoices/${invoice.id}`}>
{invoice.number}
</NavLink>
))}
</nav>
<main>
<Outlet />
</main>
</div>
);
}
If you navigate in Data Mode from /invoices/42 to /invoices/43, the outer route, whose own parameters haven’t changed, stays in place by default; its loader doesn’t run again in this example, and only the inner route switches its data and its content in the <Outlet />. Changed search parameters or a custom shouldRevalidate rule can trigger a broader revalidation. The URL then reads like a path through the tree of the UI: every segment stands for a level, every level for a route, every route for a piece of UI with its own data. A layout route without any path, by the way, can serve purely as the shared frame while its children carry the actual addresses.
The URL as state: search parameters#
So far it was about the path. The second part of the URL is at least as useful: the search parameters after the ?. In the React overview, I argued that selection and filters belong in the URL – and useSearchParams is the tool for that. It feels like useState but writes its value into the address bar.
import { useSearchParams } from "react-router";
function InvoiceFilter() {
const [searchParams, setSearchParams] = useSearchParams();
const status = searchParams.get("status") ?? "all";
return (
<select
value={status}
onChange={(event) =>
setSearchParams({ status: event.target.value })
}
>
<option value="all">All</option>
<option value="open">Open</option>
<option value="paid">Paid</option>
</select>
);
}
The selected filter is now in the URL – /invoices?status=open – and that fundamentally changes its character. This state can be shared: you send the link, and the recipient sees the same filtered list. It can be saved as a bookmark. It survives a reload because it doesn’t live in component memory but in the address. And it can be connected to the loader: since the loader has access to the request URL, it can read the status parameter and fetch the correctly filtered list from the server right away. The filter is in the URL, the loader reads it, the server delivers – a piece of UI state becomes a navigable place.
Errors and slow partial data#
Because the loader runs before rendering, failure needs a place of its own. If a loader or an action throws – such as the throw new Response(..., { status: 404 }) from above – React Router looks for the nearest route with an errorElement and renders it instead of the component. Inside the error element, you get at what was thrown with useRouteError().
import { useRouteError } from "react-router";
function RouteError() {
const error = useRouteError();
return <p role="alert">Something went wrong: {error.status}</p>;
}
This replaces many scattered if (error) branches with one place at the route level. The route error boundary handles not only errors from loader and action but also render errors in its branch of routes. The application should still model expected domain errors deliberately instead of treating every negative state as an exception.
One side topic, only touched on here: sometimes the page shouldn’t wait for the slowest data source. React Router 8 removed the former defer helper. Today, a loader returns non-critical data as a not-yet-resolved promise; in the component, <Await> waits for it inside a <Suspense> boundary. Critical data is still awaited in the loader. That way, a sluggish part doesn’t block the whole view, without needing a special defer response.
A word on the three modes#
What I’ve shown here is called Data Mode in the current documentation: createBrowserRouter in an existing application. Declarative Mode with BrowserRouter offers classic routing without the data APIs. Framework Mode builds on Data Mode, organizes routes as modules and adds build and server functions. That’s a separate, bigger topic, and I deliberately leave it aside here. The concepts that matter – loader, action, revalidation, the URL as the place for state – stay the same in Data and Framework Mode.
Where the data belongs#
The common thread of this post is a single shift. In the classic approach, loading and writing hang off the component: it renders, its effect fetches, its handlers write, and with nesting the loads line up into a waterfall. The data router anchors both at the route. The loader fetches the data before rendering, and neighboring levels in parallel; the action writes and then lets the loaders revalidate on their own. What remains in the component is displaying – not fetching.
This finally turns the URL into what the overview only claimed it was. It is no longer the address field that shows where you are. It is the place where navigable state really lives: the path determines which routes and therefore which data get loaded, the search parameters carry filters and selection, and together they can be shared, saved and survive every reload. Once you build this way, you’re happy to move the loading logic out of the component body.
Further reading#
- Repository introduction-react (routing chapter, recipes folder on data fetching): https://github.com/mikebild/introduction-react
- React Router, official documentation: https://reactrouter.com/
- React Router, “Picking a Mode”: https://reactrouter.com/start/modes
- React Router, “Data Loading”: https://reactrouter.com/start/data/data-loading
- React Router, “Actions”: https://reactrouter.com/start/data/actions
Revised and translated from German with the help of AI.