Sub topic 10
Loading data with loaders
This chapter assumes you can write React function components, use fetch with async/await, and have a router set up with createBrowserRouter and RouterProvider. It also assumes you know how to read dynamic segments with useParams.
Why loaders exist
A common pattern is to render a component, then fetch its data in useEffect. That means the page shows an empty state first. Nested routes can also start their requests one after another, because a child only renders after its parent does.
A loader moves the fetch into the route definition. React Router calls the loader when a navigation to that route starts. It waits for the data and then renders the route's element. Loaders for matched nested routes run in parallel.
Writing a loader
A loader is a function you attach to a route object. It receives an object with params (the dynamic segments) and request (a standard Request). Whatever it returns becomes the route's data.
import { createBrowserRouter, useLoaderData, useRouteError, isRouteErrorResponse } from "react-router-dom";
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.userId}`);
if (!res.ok) {
throw new Response("User not found", { status: res.status });
}
return res.json();
}
function User() {
const user = useLoaderData();
return <h1>{user.name}</h1>;
}
function UserError() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong.</p>;
}
const router = createBrowserRouter([
{
path: "/users/:userId",
element: <User />,
loader: userLoader,
errorElement: <UserError />,
},
]);The component calls useLoaderData() and gets the resolved value. There is no loading state inside User, because the component only renders once the data exists.
Errors in loaders
When a loader throws, the router skips the element and renders the nearest errorElement. Throwing a Response lets you attach a status code. isRouteErrorResponse tells you whether the error is such a response, and error.data holds its body.
Note that fetch does not reject on a 404 or 500. You must check res.ok yourself, as the example does.
Using the request
Because request is a standard Request, you can read the query string from its URL. This is how a loader reacts to search params.
export 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)}`);
if (!res.ok) throw new Response("Failed to load products", { status: res.status });
return res.json();
}Loaders run outside React, so you cannot call hooks such as useParams in them. Use the arguments instead.
Common mistakes
- Calling
useLoaderData()in a component whose route has no loader. It returnsundefined. - Forgetting the
res.okcheck, so error pages render as if they were data. - Putting browser-only secrets in a loader. The code runs in the browser and is visible to users.
- Reading
useLoaderData()in a child component and expecting the parent route's data. The hook returns data for the route that renders it.
Exercise
A route /posts/:postId has a loader that calls fetch and returns res.json(). The API responds with status 404 for a missing post, but the page shows a broken component instead of an error page. What is the likely cause, and how do you fix it?
Show answer
fetch resolves normally on a 404, so the loader returns the error body as if it were a post. Check res.ok in the loader and throw new Response("Post not found", { status: res.status }). Then add an errorElement to the route so the router renders it.