Sub topic 3
Loading Data and Managing Route Lifecycles
Assume you know React components, hooks, async/await, fetch, JSX, URLs, and browser history. This chapter uses React Router's data-router API.
Loading data with loaders
A loader fetches data before a route renders. useLoaderData reads the loader's result.
async function userLoader({ params }) {
const response = await fetch(`/api/users/${params.userId}`);
if (!response.ok) {
throw new Response("User not found", { status: response.status });
}
return response.json();
}
function User() {
const user = useLoaderData();
return <h1>{user.name}</h1>;
}Attach userLoader to the route object. React Router also cancels interrupted requests when navigation changes.
Actions and forms
An action handles a route mutation, such as creating a record. The Form component submits through the router without a full page reload.
async function createContact({ request }) {
const data = await request.formData();
await fetch("/api/contacts", {
method: "POST",
body: JSON.stringify({ name: data.get("name") }),
headers: { "Content-Type": "application/json" },
});
return redirect("/contacts");
}Use it with <Form method="post">. The route's action receives the submission.
Pending UI
useNavigation exposes navigation state. Disable a submit button while state is "submitting", or show a page-level indicator while it is "loading".
Route errors
A route can define errorElement. A loader or action can throw a Response; useRouteError reads it in the error component.
function UserError() {
const error = useRouteError();
return <p>{error.status ?? 500}: Could not load the user.</p>;
}A catch-all route such as { path: "*", element: <NotFound /> } handles unmatched URLs.
Protecting routes
A protection loader checks authentication before rendering:
function requireAuth() {
if (!localStorage.getItem("token")) throw redirect("/login");
return null;
}Treat this as a user-experience guard. The server must still authorize every protected request.
Choosing a router
| Router | Use when |
|---|---|
| Browser | Normal web hosting with server fallback |
| Hash | Hosting cannot rewrite unknown paths |
| Memory | Tests or non-browser environments |
Code splitting and testing
The lazy property loads a route module only when needed:
{ path: "/reports", lazy: () => import("./routes/reports.jsx") }Use createMemoryRouter in tests. Set initialEntries to start at a specific URL, then render RouterProvider and assert on the result.
const router = createMemoryRouter(
[{ path: "/users/:id", element: <h1>User</h1> }],
{ initialEntries: ["/users/42"] }
);
render(<RouterProvider router={router} />);
expect(await screen.findByText("User")).toBeTruthy();Exercise
Where should authorization be enforced for a protected route?
Show answer
In the server or API, with the route loader acting only as an early client-side redirect.