Loading Data Before Rendering with React Router Loaders
In React Router's data mode, if you write a loader on a route, the data is loaded before that route's component is rendered. The component only receives the loaded data with useLoaderData, so you don't need to fetch data in useEffect and render a "no data yet" state.
In a test environment, I built three nested routes (a cat list, a cat page, and a meal log). I recorded when each loader was called and when each component rendered to confirm the behavior.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 141. I used react-router 8.5.0, react / react-dom 19.3.1, @types/react 19.3.0, and typescript 7.0.2. Instead of a server, the data came from functions that wait a fixed time (300 to 800 ms) before returning. For the browser checks, I ran the code converted with esbuild (a development build) in Chromium and operated it with Playwright.
- 1. Add a loader to a route and receive the data with useLoaderData
- 2. Loaders of nested routes start at the same time
- 3. When moving between pages, the previous screen stays until loading finishes
- 4. When nothing is found, throw a 404 and display it with ErrorBoundary
- 5. If you press another link during a transition, the previous load is aborted
- 6. Let the loader handle loading, and let components focus on display
Add a loader to a route and receive the data with useLoaderData
To use a loader, follow the official installation steps. Create the router with createBrowserRouter and pass it to RouterProvider. Write loader and Component side by side in the route definition. The code in this article comes from the test code, with the timing-recording code, the routes and links for testing errors, and some imports removed.
import { createRoot } from 'react-dom/client';
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';
const router = createBrowserRouter([
{
path: '/',
loader: rootLoader,
Component: Root,
HydrateFallback: Loading,
ErrorBoundary: ErrorPage,
children: [
{ index: true, Component: Home },
{
path: 'cats/:catId',
loader: catLoader,
Component: CatPage,
ErrorBoundary: ErrorPage,
children: [{ path: 'meals', loader: mealsLoader, Component: Meals }],
},
],
},
]);
createRoot(document.getElementById('root')!).render(<RouterProvider router={router} />);
A loader is a function that returns data. The :catId part of the URL can be read as params.catId.
import { Link, Outlet, useLoaderData, type LoaderFunctionArgs } from 'react-router';
export async function catLoader({ params, request }: LoaderFunctionArgs) {
const cat = await fetchCat(params.catId!, request.signal);
// Handling the not-found case will be added in the error section below
return { cat };
}
export function CatPage() {
const { cat } = useLoaderData<typeof catLoader>();
return (
<section>
<h1>{cat.name}</h1>
<p>毛の色:{cat.color}</p>
<Link to={`/cats/${cat.id}/meals`}>ごはんの記録</Link>
<Outlet />
</section>
);
}
As described in the useLoaderData reference, writing useLoaderData<typeof catLoader>() gives the component the type of the value the loader returns. In testing, when I mistyped cat.name as cat.nam, the type checker reported this error:
errors/WrongField.tsx(6,18): error TS2551: Property 'nam' does not exist on type 'Cat'. Did you mean 'name'?
fetchCat is a function I made for testing. It waits 600 ms and then returns cat data. In a real app, you would call fetch here.
Loaders of nested routes start at the same time
When I opened /cats/1/meals directly, three routes matched the URL: the list, the cat page, and the meal log. In the test environment, I recorded when each loader started and ended, and when each component rendered. The number on the left is the time elapsed since the page was opened.
7ms rootLoader: 開始
7ms catLoader(1): 開始
7ms mealsLoader(1): 開始
7ms createRoot して描画を始める
18ms Loading(HydrateFallback)を描画
307ms rootLoader: 終了
608ms catLoader(1): 終了
808ms mealsLoader(1): 終了
809ms router: state=idle location=/cats/1/meals
812ms Root を描画(navigation.state = idle)
815ms CatPage を描画(たま)
816ms Meals を描画(2件)
All three loaders started at the same time. They did not wait for the parent loader to finish before starting the child loaders. The dataStrategy explanation also says that React Router runs all loaders in parallel by default. After the slowest loader (800 ms) finished, the three components rendered together.

While the loaders were running, the Loading component passed to HydrateFallback was displayed. At 100 ms after the page was opened, the screen showed only the loading message. HydrateFallback is displayed while loading during the first page open.
Neither CatPage nor Meals rendered before its data finished loading. You don't need to write a branch for "no data yet" inside the component.
When moving between pages, the previous screen stays until loading finishes
Next, I opened /, pressed the Tama link, and moved to /cats/1. About 200 ms after pressing the link, the URL was still /, and the previous screen (which showed the prompt to select a cat) was still displayed. The new page is displayed only after its loader finishes.
383ms router: state=loading location=/
383ms catLoader(1): 開始
390ms Root を描画(navigation.state = loading)
983ms catLoader(1): 終了
984ms router: state=idle location=/cats/1
985ms Root を描画(navigation.state = idle)
990ms CatPage を描画(たま)
If nothing changed while waiting, the person who pressed the link would not know that it worked. The guide on pending UI explains how to check whether loading is in progress with useNavigation. The data mode page says the same approach works in data mode. In testing, I added the following display to the list component:
import { Link, Outlet, useLoaderData, useNavigation } from 'react-router';
export function Root() {
const { cats } = useLoaderData<typeof rootLoader>();
const navigation = useNavigation();
return (
<div>
<nav>
{cats.map((cat) => (
<Link key={cat.id} to={`/cats/${cat.id}`}>
{cat.name}
</Link>
))}
</nav>
{navigation.state === 'loading' && <p className="pending">読み込み中…</p>}
<Outlet />
</div>
);
}
When a link was pressed, navigation.state became loading, and a loading message appeared above the previous screen.

At this point, the list's rootLoader was not called again. When I continued to the meal log by pressing the link to it and moved to /cats/1/meals, only mealsLoader was called. The route object explanation says that in data mode, a loader is called again only in three cases: when the route's URL parameters change, when the query string changes, or after an action returns a status code that is not an error. A loader for a route that is newly shown at the destination is called each time.
When nothing is found, throw a 404 and display it with ErrorBoundary
When data is not found in a loader, throw it with a status code using data(). The error handling guide also shows this way of returning a 404.
import { data } from 'react-router';
export async function catLoader({ params, request }: LoaderFunctionArgs) {
const cat = await fetchCat(params.catId!, request.signal);
if (!cat) {
throw data('猫が見つかりません', { status: 404 });
}
return { cat };
}
The thrown value is received by the component passed to the route's ErrorBoundary, using useRouteError. A value thrown with data() can be identified with isRouteErrorResponse, and it contains status and data.
import { isRouteErrorResponse, useRouteError } from 'react-router';
export function ErrorPage() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return (
<p role="alert">
{error.status}:{error.data}
</p>
);
}
const message = error instanceof Error ? error.message : '不明なエラー';
return <p role="alert">エラー:{message}</p>;
}
In testing, when I opened /cats/99 (a cat that does not exist), the page displayed "404: No cat found." The links at the top remained. This is because the ErrorBoundary attached to the cat page route displayed the error, and the list route rendered as usual.
When I opened a route whose loader threw new Error('データの読み込みに失敗しました'), the thrown error was passed to the same ErrorPage, and it displayed "Error: failed to load data."
If you press another link during a transition, the previous load is aborted
A loader receives request as an argument. In catLoader above, I passed request.signal to fetchCat. The fetchCat used in testing is written so that when this signal is aborted, it stops waiting and leaves a log.
I pressed the Kuro link, then pressed the Shiro link about 100 ms later, before the Kuro loading finished.
389ms catLoader(2): 開始
396ms Root を描画(navigation.state = loading)
519ms fetchCat(2): 中止された(signal.aborted = true)
519ms router: state=loading location=/
519ms catLoader(3): 開始
529ms Root を描画(navigation.state = loading)
1120ms catLoader(3): 終了
1120ms router: state=idle location=/cats/3
1121ms Root を描画(navigation.state = idle)
1122ms CatPage を描画(しろ)
When Shiro was pressed, the signal of the Kuro loading was aborted, and the Kuro page was never rendered. The last page displayed was the Shiro page. The official explanation of how overlapping operations are handled also says that when another navigation starts during a navigation, the request for the earlier navigation is aborted. In an actual app, if you pass signal: request.signal to fetch, as in the official example, the browser's network request is also cut off when it is aborted. In testing, I did not use fetch, so I did not test this part.
According to the same explanation, aborting on the browser side does not stop a request that has already been sent from reaching the server. Aborting on the browser side only frees browser resources. It cannot prevent the request from reaching the server.
Let the loader handle loading, and let components focus on display
In React Router's data mode, you can load data before rendering just by writing loader on a route and calling useLoaderData<typeof loader>() in the component. In testing, the loaders of nested routes started at the same time and all rendered after they finished. While navigating, the previous screen stays until loading completes, so I show a loading message with useNavigation. If nothing is found, throw a 404 with data() and display it with ErrorBoundary. If you move to another page midway, the request.signal of the earlier load is aborted. If you pass this signal to the loading process that responds to aborts, unneeded loads can be stopped midway.





