Load route data and handle errors
Load a record before displaying it
A loader connects data to a matched route. It receives information such as path parameters and a Request. In the following client-only examples, data is synthetic and held in local memory. The router can wait for the loader result and make it available to useLoaderData. Unlike useEffect, a loader is not tied to a component Effect lifecycle. Each full example is a separate App.jsx inside the approved Chapter 3 client project, without an extra router.
import React from 'react';import { createMemoryRouter, useLoaderData } from 'react-router';import { RouterProvider } from 'react-router/dom';function findBook(id) { return [{id:'atlas', title:'Pocket Atlas'}, {id:'garden', title:'City Gardens'}].find(book => book.id === id);}function Book() { const book = useLoaderData(); return <main><h1>{book.title}</h1></main>;}const router = createMemoryRouter([{path:'/books/:id', loader: ({params}) => { const book = findBook(params.id); if (!book) throw new Response('Not found', {status:404}); return book;}, Component:Book, errorElement:<p role="alert">Book unavailable.</p>}], {initialEntries:['/books/atlas']});export default function App() { return <RouterProvider router={router} />; }The initial entry matches /books/:id and the loader returns Pocket Atlas. An unknown ID throws a response instead of sending undefined into the component. A client-side route error with status 404 does not establish an HTTP 404 from a host. Never treat a path parameter as authorization.
Separate a missing record from an unexpected failure
import React from 'react';import { createMemoryRouter, useRouteError, isRouteErrorResponse, Link } from 'react-router';import { RouterProvider } from 'react-router/dom';function messageForStatus(status) { return status === 404 ? 'Book not found.' : 'Unable to open the book.';}function Boundary() { const error = useRouteError(); return <main><h1 role="alert">{messageForStatus(isRouteErrorResponse(error) ? error.status : undefined)}</h1> <Link to="/">Return to library</Link></main>;}const router = createMemoryRouter([{path:'/', element:<h1>Library</h1>}, {path:'/missing', loader:() => {throw new Response('Not found', {status:404});}, element:<h1>Book</h1>, ErrorBoundary:Boundary}], {initialEntries:['/missing']});export default function App() { return <RouterProvider router={router} />; }Expected: Book not found and a recovery link. A route boundary handles failures in its route loading, action or rendering path, with errors bubbling to a matching ancestor boundary when appropriate. Keep a safe generic message for unexpected errors and log details only in an authorized environment. Normal form validation should be returned as data rather than thrown as a crash. A route boundary does not catch arbitrary event handler errors.
Show navigation progress without replacing the whole app
import React from 'react';import { createMemoryRouter, useLoaderData, useNavigation, Outlet, Link } from 'react-router';import { RouterProvider } from 'react-router/dom';function Layout() { const navigation = useNavigation(); return <main><nav><Link to="/">Home</Link>{' | '}<Link to="/catalog">Catalog</Link></nav> <p role="status">{navigation.state !== 'idle' ? 'Loading catalog…' : ''}</p><Outlet /></main>;}function Catalog() { const books = useLoaderData(); return <ul>{books.map(book => <li key={book}>{book}</li>)}</ul>; }const router = createMemoryRouter([{path:'/', Component:Layout, children:[ {index:true, element:<h1>Library home</h1>}, {path:'catalog', loader:async () => {await new Promise(resolve => setTimeout(resolve, 300)); return ['Pocket Atlas','City Gardens'];}, Component:Catalog}]}]);export default function App() { return <RouterProvider router={router} />; }Click Catalog: a pending message may appear while the loader is waiting; the expected settled screen lists two books. Timing and announcements require browser tests; a 300 ms delay is illustrative, not a guarantee of a visible frame. In real network loaders pass request.signal into supported cancellable APIs and handle errors. The local timer does not demonstrate cancellation. Avoid duplicate loading flags for the same navigation; fetcher state (next lesson) tracks independent work.
Practice
Add a third book, test a valid and missing ID, and change the error fixture to throw an ordinary Error. Predict the visible messages, then verify actual routing in a reviewed harness.