Sub topic 10
Loading data with loaders
This chapter assumes you can define routes with createBrowserRouter, nest them with Outlet, and read params with useParams. It also assumes you know fetch and async/await. Here you will move data fetching out of useEffect and into the route definition.
Why loaders exist
A common first approach is to render a component, start a fetch inside useEffect, and show a spinner until the data arrives. This causes a "render, then fetch" waterfall. The route renders empty, the effect runs, and the data arrives later. A nested child route can't start its own fetch until its parent has rendered.
A loader is a function attached to a route. The router calls it when a navigation to that route begins. It waits for the returned data, then renders the route with the data already in hand. Loaders for all matched routes in a nested tree start in parallel, so a parent and its child fetch at the same time.
The sequence for one navigation looks like this:
During the wait, the previous page stays on screen. The URL changes only after the loaders finish. Chapter sections on pending UI show how to signal this wait to the user.
A basic loader
A loader is an async function that receives an object with params and request. Whatever it returns becomes the route's data. The component reads that data with useLoaderData.
import { createBrowserRouter, RouterProvider, useLoaderData } from "react-router-dom";
async function usersLoader({ request }) {
const res = await fetch("/api/users", { signal: request.signal });
if (!res.ok) {
throw new Response("Could not load users", { status: res.status });
}
return res.json();
}
function Users() {
const users = useLoaderData();
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}
const router = createBrowserRouter([
{ path: "/users", element: <Users />, loader: usersLoader },
]);
export default function App() {
return <RouterProvider router={router} />;
}Three details matter here:
request.signalis anAbortSignal. If the user clicks another link before the fetch finishes, the router aborts it. Passing the signal tofetchcancels the network request.- The loader returns the parsed JSON. You can also return a
Response, and the router will parse the body for you. Returning plain values is clearer. useLoaderDatahas no loading state. By the time the component renders, the data exists.
Using params and the request URL
A loader runs outside React, so it can't call useParams or useSearchParams. It gets the same information from its argument.
paramsholds dynamic segments. For the pathusers/:userId, readparams.userId.requestis a standardRequest. Build aURLfromrequest.urlto read the query string.
async function productsLoader({ request }) {
const url = new URL(request.url);
const sort = url.searchParams.get("sort") ?? "name";
const res = await fetch(`/api/products?sort=${encodeURIComponent(sort)}`, {
signal: request.signal,
});
if (!res.ok) {
throw new Response("Could not load products", { status: res.status });
}
return res.json();
}
async function userLoader({ params, request }) {
const res = await fetch(`/api/users/${encodeURIComponent(params.userId)}`, {
signal: request.signal,
});
if (!res.ok) {
throw new Response("User not found", { status: res.status });
}
return res.json();
}Encode values with encodeURIComponent before placing them in a URL. Both params and query strings come from the address bar, which the user controls.
When loaders run again
A loader does not run only once per route. The router re-runs loaders, a step called revalidation, in these cases:
- The route's params change, for example from
/users/1to/users/2. - The query string changes, for example when a
setSearchParamscall updates?sort=price. - An action finishes on any route. After a form submission, all active loaders run again so the page shows fresh data.
- The user navigates to the same URL again.
Case 2 surprises many people. A search box that updates ?q= triggers the loader on every change. The request.signal abort from the earlier example prevents stale responses from overwriting newer ones.
Navigating between two child routes does not re-run the parent's loader unless one of the cases above applies. The router skips loaders whose route params and URL did not change in a way that affects them.
Loaders in nested routes
Each route in a nested tree can have its own loader. The router runs them together, and each component reads only its own route's data.
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
loader: async () => fetch("/api/session").then((r) => r.json()),
children: [
{ path: "users/:userId", element: <User />, loader: userLoader },
],
},
]);Inside Layout, useLoaderData() returns the session. Inside User, it returns the user. The hook always returns data for the route that renders the calling component.
A child's loader cannot read the parent's loader result directly, because both run at the same time. If a child needs the parent's data, fetch it again in the child or restructure the data so each route is independent.
Errors, 404s, and redirects
A loader signals failure by throwing. The router stops rendering the route and shows the nearest errorElement on the route or one of its ancestors.
- Throw a
Responsefor expected failures such as a 404. The error element detects it withisRouteErrorResponse. - Any other thrown value, such as a network
TypeError, arrives atuseRouteErroras is. - Throw
redirect("/login")to send the user elsewhere. This is the basis of protected routes.
import { useRouteError, isRouteErrorResponse } from "react-router-dom";
function UserError() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong.</p>;
}Attach it with errorElement: <UserError /> on the route. If the route has no errorElement, the error bubbles up to the parent. If no route handles it, the router shows a default error page.
Common mistakes
- Returning
undefined. A loader must return a value or aResponse. If a branch has no data, returnnull. TherequireAuthloader from the protected routes section returnsnullfor this reason. - Calling hooks in a loader. Loaders are plain functions.
useParams,useNavigate, and context values are not available. Pass what you need throughparams,request, or a module-level value. - Checking
res.oktoo late.fetchresolves even for 404 and 500 responses. If you skip theres.okcheck,res.json()may fail on an error page, or the component may receive an error payload as if it were data. - Using
useLoaderDatain the wrong place. It reads the nearest route's data. A component rendered outside a route with a loader getsundefined. A shared component used in several routes should receive data as props instead. - Putting everything in loaders. Data that changes with user interaction after the page is shown, such as a live search suggestion list, often belongs in component state or a data-fetching library. Loaders fit data the page needs to display on arrival.
Testing a loader
Because a loader is a function, you can call it directly in a test with a fake params and request. You can also render a route with createMemoryRouter and a mocked fetch, then assert on the output. The testing chapter covers this in detail.
Exercise
A route /search has a loader that reads ?q= from request.url. The user types into a search box that calls setSearchParams({ q: value }) on each keystroke. What happens to the loader, and how do you keep a slow earlier response from overwriting a newer one?
Show answer
Each query string change triggers revalidation, so the loader runs again on every keystroke. The router aborts the previous navigation's request.signal. If you pass request.signal to fetch, the earlier request is cancelled, and only the latest result is rendered.
Exercise
A loader for users/:userId calls fetch and then return res.json() without checking res.ok. The API responds with status 404 and a JSON body. What does the User component receive, and how do you change the loader so the errorElement shows instead?
Show answer
The component receives the parsed 404 body as if it were a valid user, because fetch does not reject on HTTP error statuses. Add if (!res.ok) { throw new Response("User not found", { status: res.status }); } before returning, so the router renders the nearest errorElement.