Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 50 ยท Practice and Review

Exercises: Data Mode

Eight React Router data mode exercises on loaders, actions, pending UI, optimistic updates, error boundaries and revalidation. Four runnable, four real-code, all with solutions.

Data mode moves loading and saving out of your components and into the router: a loader fetches before the page renders, an action handles a form submission, and the router keeps everything in step afterward. The ideas are simple, but the details (what runs in parallel, what is pending when, which error boundary catches what) are where bugs hide. These eight exercises drill them. They accompany the Data Mode chapter, from loaders to error handling.

As in the declarative exercises, the page has two kinds of task, because React Router itself cannot run in the live editor:

  • Logic exercises (2, 4, 5 and 7) are runnable. You get a function stub and a table of tests, and you edit the function until every row says pass. Each one is a small, pure version of something the real router does for you.
  • Design exercises (1, 3, 6 and 8) use the real React Router 7 API. You write the loader, action or configuration yourself and compare it with the solution. Their code is read-only, because the editor cannot install the package.

Try each exercise for at least five minutes before opening the hint. In the design exercises, assume this setup, and notice the two imports: in v7 the DOM-specific RouterProvider lives in react-router/dom.

JSX
// main.jsx - React Router (read-only)
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';
import { createRoot } from 'react-dom/client';

const router = createBrowserRouter(routes);
createRoot(document.getElementById('root')).render(<RouterProvider router={router} />);

Loaders

1. A loader with a 404 (design)

The route /users/:id must load a user from GET /api/users/:id before its component renders. If the API answers 404, show the route's error screen with the status 404. If it fails in any other way, throw a generic error. Write the loader and the component that shows the user's name. Do not use useEffect or useState.

Show hint

A loader is an async function that receives { params, request } and returns the data (see Loaders). The component reads it with useLoaderData(). To report an HTTP-style error, throw data(message, { status: 404 }), where data is exported by react-router. Throwing anything makes the router render the route's error boundary instead of the component.

Show solution
JSX
// users.jsx - React Router (read-only)
import { data, useLoaderData } from 'react-router';

export async function userLoader({ params }) {
  const response = await fetch('/api/users/' + encodeURIComponent(params.id));
  if (response.status === 404) {
    throw data('User not found', { status: 404 });
  }
  if (!response.ok) {
    throw new Error('The user service answered ' + response.status);
  }
  return response.json();
}

export function User() {
  const user = useLoaderData();
  return <h1>{user.name}</h1>;
}

// in the route table
{ path: 'users/:id', element: <User />, loader: userLoader, errorElement: <UserError /> }

Two details matter. The component has no loading branch: it only renders when the data exists, because the router waits for the loader. And the id is encoded before it goes into a URL, since params.id came from the address bar and may contain / or ?. The two kinds of throw reach the boundary in different shapes: data(...) becomes an error response with a status, while new Error(...) arrives as a plain error. Exercise 6 handles both.

2. Run all loaders at once (logic)

When the URL matches a layout, a section and a page, each route may have a loader, and the router starts them all together, not one after another. Write loadAll(loaders). It takes an array of loader functions (an entry can be null for a route without a loader) and returns a promise of { data, error }. data has one entry per loader (null for a missing loader, and undefined for a failed one). error is null when everything worked, or { index, value } for the first failed loader. A loader may fail by returning a rejected promise or by throwing synchronously.

Exercise 2: loadAll (starter)
Show hint

Promise.allSettled(promises) waits for every promise and never rejects; each result is { status: 'fulfilled', value } or { status: 'rejected', reason }. To also catch a loader that throws synchronously, do not call the loaders directly: map them through an async arrow function, which turns a throw into a rejection. Use findIndex for the first rejected result.

Show solution
Solution 2: loadAll

The map calls every loader immediately, so they run in parallel, and allSettled only decides when to collect. If you wrote for (const loader of loaders) { await loader(); } instead, the total time would be the sum of the loaders (a waterfall) instead of the slowest one.

flowchart LR
    subgraph P["Parallel: total = slowest"]
        direction LR
        A1["layout loader 200 ms"]
        A2["page loader 300 ms"]
    end
    subgraph W["Waterfall: total = sum"]
        direction LR
        B1["layout loader 200 ms"] --> B2["page loader 300 ms"]
    end

The router starts every matched loader together, so this page waits about 300 ms. A hand-written waterfall would wait 500 ms.

The real router adds more rules (it only re-runs loaders whose data may have changed, and it lets a thrown error pick its boundary), but the core is this function. See Loaders: Data Before Render for the details.

Actions

3. A form with validation and a redirect (design)

Write the page for /contacts/new. It has a form with a required name field and an optional email. On submit, an action validates the data: if the name is empty, the page must show an error message next to the field and stay where it is, keeping what the user typed. If the data is valid, save the contact with saveContact(values) (it returns the new contact with an id) and navigate to /contacts/<id>. While the action runs, the button must say "Saving..." and be disabled.

Show hint

Use the router's Form component (not <form>), so that a submission goes to the route's action without a page reload. The action receives { request }; read the fields with await request.formData(). Return an object for validation errors (the component reads it with useActionData()), and return redirect(...) for success. Pending state comes from useNavigation().state. See Actions and Form and Pending and Optimistic UI.

Show solution
JSX
// NewContact.jsx - React Router (read-only)
import { Form, redirect, useActionData, useNavigation } from 'react-router';

export async function newContactAction({ request }) {
  const formData = await request.formData();
  const name = String(formData.get('name') ?? '').trim();
  const email = String(formData.get('email') ?? '').trim();

  if (name === '') {
    return { errors: { name: 'Please enter a name.' } };
  }
  const contact = await saveContact({ name, email });
  return redirect('/contacts/' + contact.id);
}

export function NewContact() {
  const actionData = useActionData();
  const navigation = useNavigation();
  const saving = navigation.state === 'submitting';

  return (
    <Form method="post">
      <label>
        Name <input name="name" />
      </label>
      {actionData?.errors?.name && <p role="alert">{actionData.errors.name}</p>}
      <label>
        Email <input name="email" type="email" />
      </label>
      <button type="submit" disabled={saving}>
        {saving ? 'Saving...' : 'Save'}
      </button>
    </Form>
  );
}

// in the route table
{ path: 'contacts/new', element: <NewContact />, action: newContactAction }

Notice what the component does not have: no onSubmit, no preventDefault, no useState for errors or for "saving". Returning data keeps the page mounted, so the inputs keep their text. The redirect makes the router navigate and then re-run the loaders of the new URL. Because Form renders a real HTML form, this also works with JavaScript disabled when the app is server-rendered.

Pending UI and optimistic updates

4. Derive the pending state (logic)

A save button must show the right label for the current navigation. Write pendingUi(navigation). It receives an object like the one useNavigation() returns, { state, formData }, and returns { busy, label }. A form submission is in progress from the moment it is sent until the page it leads to has loaded: that covers state: 'submitting' (the action is running) and state: 'loading' with formData (the action finished and the loaders are running). A plain state: 'loading' without formData is just a link click, which says nothing about our form. When the form is in progress, return { busy: true, label: 'Saving...' }; otherwise { busy: false, label: 'Save' }.

Exercise 4: pendingUi (starter)
Show hint

Two conditions make the form busy: navigation.state === 'submitting', or navigation.state === 'loading' together with a truthy navigation.formData. Compute one boolean and build the object from it.

Show solution
Solution 4: pendingUi

In the real router the submitted formData stays on navigation while the loaders run after the action, which is what makes this distinction possible (the stand-in used in the project lessons clears it earlier, so it only shows submitting). The key idea is that pending state is derived: you never write setSaving(true), so you cannot forget setSaving(false) when something fails.

5. Optimistic list (logic)

A to-do list shows checkboxes. Each checkbox submits through its own fetcher, and while a request is pending you want the box to show the new value at once. Write applyOptimistic(todos, pending): todos is the list from the loader ({ id, title, done }) and pending is the list of in-flight changes ({ id, done }), oldest first, taken from the fetchers' formData. Return a new list in which every todo with a pending change shows the latest pending done. Ignore changes for unknown ids and never modify the input.

Exercise 5: applyOptimistic (starter)
Show hint

Use todos.map(...). For each todo, pending.filter((change) => change.id === todo.id) gives its changes; if there are none, return the todo itself; otherwise return { ...todo, done: lastChange.done }. map and the spread operator never modify the originals.

Show solution
Solution 5: applyOptimistic

In a real app you rarely need this whole function. With one fetcher per row, each row simply reads its own value: const done = fetcher.formData ? fetcher.formData.get('done') === 'true' : todo.done. The function above is what you need when the pending changes live somewhere central, for example when you read all active fetchers with useFetchers() to show an optimistic total count at the top of the list. Either way, a failed request needs no rollback code: once the fetcher is idle again, the pending change disappears and the loader's value shows.

Errors and revalidation

6. An error boundary that tells 404 from a crash (design)

Write the UserError component for the route from exercise 1. For a thrown 404 response it should show "We could not find that user" and the server's message. For any other thrown value it should show "Something went wrong" and, for real Error objects, the error's message. For a status other than 404 (such as 401) show the status code.

Show hint

useRouteError() returns whatever was thrown. A response created with data(...) is recognized by isRouteErrorResponse(error), which narrows it to an object with status, statusText and data. Check that first, then error instanceof Error, then fall back to a generic message. Read Error Boundaries and Error Elements if you have not yet.

Show solution
JSX
// UserError.jsx - React Router (read-only)
import { isRouteErrorResponse, Link, useRouteError } from 'react-router';

export function UserError() {
  const error = useRouteError();

  if (isRouteErrorResponse(error)) {
    if (error.status === 404) {
      return (
        <section>
          <h1>We could not find that user</h1>
          <p>{error.data}</p>
          <Link to="/users">All users</Link>
        </section>
      );
    }
    return <h1>Request failed with status {error.status}</h1>;
  }

  return (
    <section>
      <h1>Something went wrong</h1>
      {error instanceof Error && <p>{error.message}</p>}
    </section>
  );
}

Order matters: a thrown response is not an Error instance, so test isRouteErrorResponse first. Never show raw error messages to visitors in production if they could contain internal details; log them and show a friendly text instead. Also remember that the boundary only replaces this route: layouts above it, such as a header, keep rendering.

7. Find the error boundary (logic)

When a loader fails, the router does not blame the whole page. It renders the error element of the nearest route at or above the one that failed. Write findBoundary(matches, failedIndex). matches lists the matched routes from the outermost layout to the page, each { hasError: boolean } (true when the route has an errorElement). Return the index of the nearest route at or above failedIndex that has one. If none does, return 0: the root route shows the router's default error screen.

Exercise 7: findBoundary (starter)
Show hint

Count down from failedIndex to 0 and return the first index whose entry has hasError. If the loop ends without finding one, return 0.

Show solution
Solution 7: findBoundary

This is the rule behind a design decision from the notes project: put an errorElement on a pathless child of a layout, and a failing page replaces only that area, not the sidebar around it.

flowchart TD
    A["0 Root layout (errorElement)"] --> B["1 Section layout"]
    B --> C["2 Users route (errorElement)"]
    C --> D["3 User page loader throws"]
    D -. "boundary found at 2" .-> C

A failure in route 3 is caught by route 2. A failure in route 1 would be caught by route 0.

8. Skip an unnecessary revalidation (design)

A notes app has a layout route whose loader returns the sidebar list, and a child route /notes/:id whose loader returns one note. Each row in the sidebar has a pin button that posts through a fetcher to the resource route /notes/:id/pin. After a pin, the router re-runs every loader on the page by default, so the open note is fetched again for nothing. Write a shouldRevalidate function for the note route that skips revalidation after a pin, but keeps the default behavior for everything else (edits to this note, navigations).

Show hint

shouldRevalidate receives an object that includes formAction (the path the form was submitted to, as a string, when a submission caused the check) and defaultShouldRevalidate (what the router would do on its own). Return false for the pin case and the default for all others. The details are in Revalidation and Caching.

Show solution
JSX
// routes (excerpt) - React Router (read-only)
{
  path: ':id',
  element: <Note />,
  loader: noteLoader,
  shouldRevalidate: ({ formAction, defaultShouldRevalidate }) => {
    if (formAction?.endsWith('/pin')) {
      return false;
    }
    return defaultShouldRevalidate;
  },
},

Always return defaultShouldRevalidate in the fallback instead of true: the default already handles the cases where a param changed or the same URL was submitted again, and hard-coding true would revalidate when it should not. Use this tool with care. Skipping a revalidation is an optimization, and it is only correct when you are certain the skipped data cannot have changed. If a pin changed anything the note page displays (say, a "pinned" badge), skipping would show stale data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A page matches a layout route, a section route and a page route, and each has a loader. How does the router run them?

    Matched loaders are started together. A hand-written await chain would create a waterfall, which is the thing the router is designed to avoid.
  2. 2. Where should a form action put a validation error that the user can fix?

    A returned value keeps the current page mounted, so the form keeps its inputs, and useActionData hands the component the message. A throw would replace the route with its error boundary.
  3. 3. navigation.state is 'loading' and navigation.formData is set. What is happening?

    Loading with formData means a submission is finishing. Loading without formData is a normal navigation.
  4. 4. A loader for a deeply nested page throws, and only the root route has an errorElement. What renders?

    The router looks for the nearest boundary at or above the failed route. If only the root has one, everything it contains is replaced. Add boundaries lower in the tree to keep layouts visible.
  5. 5. Why is useNavigation (or a fetcher's own state) better for pending UI than your own isSaving state?

    Manually toggled flags can get stuck when a request fails or a component unmounts. Router state always matches what the router is really doing.

Summary

  • Matched loaders start together; the page waits for the slowest. Write loaders so that they do not depend on each other, and keep the component free of loading branches.
  • Return what a user can fix from an action and render it with useActionData; throw what only a developer can fix, and let an error boundary show it.
  • Pending state comes from useNavigation (and from a fetcher's own state and formData). Derive labels and disabled states from it.
  • An optimistic value is read from the pending formData and falls back to loader data, so no rollback code is needed.
  • A failure renders the nearest errorElement at or above the failing route. Place boundaries to decide how much of the page survives.
  • shouldRevalidate can skip refetching, but always fall back to defaultShouldRevalidate.

Next: Migrating From v5, v6 and Remix