Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 50 ยท Projects

Project: A Notes App with Actions and Optimistic UI

Build a notes app around loaders and actions: list, create, edit and delete notes, show pending states, handle validation and server errors, and update the screen optimistically.

A notes app is a good test of the data side of a router. Reading is easy: a loader fetches the list, another fetches one note. The interesting part is writing. Every create, edit and delete has to talk to a server that is slow and sometimes says no, and the screen must stay honest while that happens: show that something is saving, show validation messages next to the field, show a clear error when the server fails, and make quick actions such as pinning feel instant.

React Router's data mode was designed for exactly this loop: submit, run an action, revalidate the loaders, render fresh data. In this project you build that loop yourself on top of React and location.hash, so you can see every moving part, and then you compare it with the real React Router code. If the vocabulary is new, read Loaders, Actions and Form, useFetcher and Pending and Optimistic UI first.

Real library or stand-in? React Router cannot be installed in the live editor, so the runnable code uses a hand-written data router of about 190 lines: nested route objects, loaders that run in parallel, actions, Form, useFetcher, useNavigation, useActionData, error elements and revalidation. The names match the real hooks, and the real React Router version of the app is shown in read-only blocks. The stand-in is simpler than the real thing: it re-runs every matched loader after each navigation (the real router only re-runs the loaders whose route or params changed), its actions receive a plain object instead of a Request, and it has no method or action URLs.

The plan

The app has five screens and three kinds of failure.

URL Screen Loader Action
/ Welcome text next to the list list of notes (layout) none
/new Create form none createNote
/:id One note with Edit and Delete noteLoader deleteNote
/:id/edit Edit form noteLoader updateNote
every row Pin button none setPinned (fetcher)

The failures:

  • Validation errors are expected. The action returns them, and the form shows them. Nothing navigates.
  • A missing note (/99) throws from a loader. The nearest error element renders in place of that route only.
  • A server failure is unexpected. The action throws, and an error element in a pathless route replaces the page while the sidebar survives.
sequenceDiagram
    participant U as User
    participant R as Router
    participant A as Action
    participant L as Loaders
    U->>R: submit the form
    R->>A: run the action, state is submitting
    A-->>R: redirect, or errors, or a thrown error
    R->>L: revalidate every loader, state is loading
    L-->>R: fresh data
    R-->>U: render the new screen, state is idle

One submission passes through three navigation states. The page you see during the first two is the old one.

The rule of thumb behind the table: return what a user can fix (a short title), throw what only a developer or an operator can fix (a failed request). Returned values reach useActionData; thrown values reach the error element.

Step 1: the router and read-only notes

First the foundation, with the write paths left out. The api object stands in for a server: it waits 300 ms, so you can see the loading state, and the detail request throws for an unknown id. The route tree has a layout route at / whose loader supplies the list, and a child route :id whose loader fetches one note and has its own errorElement.

Read the router part once. matchRoutes finds the chain of routes for a URL, RouterProvider runs all their loaders at once with Promise.allSettled and commits the result together (so a layout never shows new data next to old data), and Level/Outlet render the chain. A loader that throws marks the route as failed, and findBoundary walks up from it to the nearest route that has an errorElement.

Step 1: the data router and read-only notes

Click a note: the sidebar says "loading..." for a moment and the old page stays on screen until the new data is ready. That is the difference between a loader and fetching in an effect (see Loaders). Now click the missing note. The error element renders inside the layout, because the failed route is :id and that route owns the nearest errorElement. The sidebar did not disappear.

Here is the same route tree written with the real React Router (read-only, v7 data mode):

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

async function listLoader() {
  return api.list();
}

async function noteLoader({ params }) {
  const note = await api.get(params.id);
  if (!note) {
    throw data('Note not found', { status: 404 });
  }
  return note;
}

const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    loader: listLoader,
    children: [
      { index: true, Component: Welcome },
      { path: ':id', Component: NoteView, loader: noteLoader, ErrorBoundary: NoteMissing },
    ],
  },
]);

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

Two small differences show up. The real router calls the property ErrorBoundary (or errorElement when you pass an element instead of a component), and Component replaces element. A thrown data(...) response carries its status, and useRouteError() plus isRouteErrorResponse() let the boundary read it (see Error Boundaries and Error Elements).

Step 2: actions for create, edit and delete

An action is an ordinary async function. It receives the submitted values, talks to the server and answers with one of three things:

  1. { errors }: validation failed. The router stores it for useActionData() and does nothing else, so the form keeps what the user typed.
  2. { redirect }: success. The router navigates (or revalidates, if the URL would not change) and the loaders run again, so the sidebar shows the new note without any manual cache update.
  3. a thrown error: something unexpected broke. The router renders the nearest error element.

Validation is a plain function you can test without React:

JavaScript
function validate(values) {
  const errors = {};
  if (values.title.trim().length < 3) {
    errors.title = 'Give the note a title of at least 3 characters.';
  }
  return errors;
}

The create, update and delete actions then become short. They only decide what the server should do and where the user goes next:

JavaScript
async function createNote({ formData }) {
  const errors = validate(formData);
  if (Object.keys(errors).length > 0) {
    return { errors };
  }
  const note = await api.create(formData);
  return { redirect: '/' + note.id };
}

Notice what is missing: no useState for the list, no setNotes, no effect that refetches after saving. The list is not copied into component state at all. After the action finishes, the router revalidates the loaders, and the screen is rebuilt from the server's answer. This removes a whole class of bugs where local state and server data drift apart.

Step 3: pending state

While an action runs, useNavigation() reports state === 'submitting', and navigation.formData holds the values that were sent. When the action is done and the loaders are re-running, the state is 'loading'. Use them for three jobs:

  • Disable the submit button and change its label ("Saving...") so a second click cannot create a duplicate.
  • Show a global indicator (the small status text in the sidebar).
  • Dim or hide what is about to change.

Pending state is derived from the router, so you never write setSaving(true) and setSaving(false). That also means you cannot forget to reset it when an error happens.

Step 4: optimistic pinning with a fetcher

Pinning a note is a small, almost always successful change. Waiting 400 ms to see a star fill in feels sluggish, but navigating anywhere would be wrong, because the user is still reading. This is the job of useFetcher(): it submits an action without navigation, and each fetcher has its own state, so several rows can be pending at once.

The optimistic trick is one line. While the fetcher is submitting (or reloading), read the value from fetcher.formData, the value the user just asked for. When the fetcher is idle again, read it from the loader data:

JavaScript
const pinned = fetcher.formData ? fetcher.formData.pinned === 'true' : note.pinned;

There is no rollback code. If the server refuses, the action returns { error }, the fetcher goes back to idle, fetcher.formData becomes null, and the star flips back to the loader's value by itself. The state was never stored, only derived. The demo server refuses to pin note 3 so you can watch that.

Step 5: the full app

Everything together. Things to try:

  1. Click + New note, press Create note with an empty title: the validation message appears and the form keeps its place.
  2. Create a note titled Water the plants: the button shows "Saving...", then the app redirects to the new note and the sidebar lists it.
  3. Create a note titled This will fail: the fake server throws, the page area shows the error element and the sidebar stays. Try again revalidates.
  4. Pin note 1: the star fills at once, and the order in the sidebar changes after the reload. Pin note 3: the star fills, then flips back and a message explains why.
  5. Open Edit, change the title and save. Delete a note and watch the redirect.
Step 5: notes with actions, pending state and optimistic pinning

A few design points worth noticing in the code:

  • The pathless route (the one with only errorElement and children) exists just to scope the error boundary. A throw in createNote replaces the page area, not the sidebar. See Layout Routes and Pathless Routes.
  • key={note.id} on the edit form resets the uncontrolled inputs when you move from one note's edit page to another. Without it, React would reuse the same inputs and keep the old text.
  • NoteFields is shared between create and edit, so the validation message and the pending label are written once.
  • Rows do not know about each other. Each NoteRow owns a fetcher, so pinning two notes in a row gives two independent pending states.

The real React Router version

The actions of the real router receive a Request, so they read the form with request.formData(). The same app, read-only:

JSX
// actions.js - React Router (read-only)
import { redirect } from 'react-router';

export async function createNote({ request }) {
  const formData = await request.formData();
  const values = Object.fromEntries(formData);
  const errors = validate(values);
  if (Object.keys(errors).length > 0) {
    return { errors };
  }
  const note = await api.create(values);
  return redirect('/' + note.id);
}

export async function deleteNote({ params }) {
  await api.remove(Number(params.id));
  return redirect('/');
}

export async function setPinned({ request, params }) {
  const formData = await request.formData();
  try {
    await api.setPinned(Number(params.id), formData.get('pinned') === 'true');
    return { ok: true };
  } catch (error) {
    return { error: error.message };
  }
}

The route table attaches actions to paths. A route with an action and no component is called a resource route here, and it is the usual home for fetcher-only actions such as pinning:

JSX
// routes (excerpt) - React Router (read-only)
{ path: 'new', Component: NewNote, action: createNote },
{ path: ':id', Component: NoteView, loader: noteLoader, action: deleteNote, ErrorBoundary: NoteMissing },
{ path: ':id/pin', action: setPinned },

And the components use the real hooks with the same names as the stand-in:

JSX
// NoteRow.jsx - React Router (read-only)
import { Link, useFetcher } from 'react-router';

export function NoteRow({ note }) {
  const fetcher = useFetcher();
  const pinned = fetcher.formData ? fetcher.formData.get('pinned') === 'true' : note.pinned;

  return (
    <li>
      <fetcher.Form method="post" action={'/' + note.id + '/pin'}>
        <input type="hidden" name="pinned" value={String(!pinned)} />
        <button aria-pressed={pinned}>{pinned ? 'โ˜…' : 'โ˜†'}</button>
      </fetcher.Form>
      <Link to={'/' + note.id}>{note.title}</Link>
      {fetcher.data?.error && <p role="alert">{fetcher.data.error}</p>}
    </li>
  );
}

The real fetcher.formData is a FormData object, so you read it with .get('pinned'); the stand-in uses a plain object, which is why the live code writes formData.pinned. In the real router, forms also work without JavaScript as ordinary HTML form posts, which is a major reason to prefer Form over a hand-written onSubmit.

Ideas to extend it

  • Add a search box that keeps its text in the URL (Search Params) and filters in the loader.
  • Add an undo after delete: keep the removed note in the action's return value and offer a button that submits createNote again.
  • Show a toast when fetcher.data changes, instead of an inline message.
  • Add a shouldRevalidate function so that pinning does not refetch the open note (Revalidation and Caching).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A form action finds that the title is too short. What should it do so that the user keeps what they typed and sees a message next to the field?

    Expected, fixable problems are returned from the action. The router keeps the current page mounted, so the form and its inputs stay as they are, and useActionData gives the component the errors. Throwing replaces the route with its error element.
  2. 2. In the pin button, why is there no code that restores the old star when the server refuses?

    The optimistic value is derived, not stored. When the fetcher goes idle, formData is gone, so the component renders the (unchanged) loader value again. Nothing has to be undone.
  3. 3. Why does the project use a pathless route that only has an errorElement and children?

    An error replaces the route that owns the nearest boundary. By putting the boundary on a pathless child of the layout, the layout itself keeps rendering.
  4. 4. After a successful createNote, how does the new note appear in the sidebar?

    After an action finishes, the router re-runs the loaders for the current page. The list is never copied into component state, so there is nothing to keep in sync by hand.
  5. 5. While an action is running, what does navigation.state report?

    The states are idle, submitting (the action is running) and loading (loaders are running after the action or during a navigation).

Summary

  • Data mode turns writing into a loop: submit, run the action, revalidate the loaders, render fresh data. The list lives in the loader, not in component state.
  • Return expected problems (validation) from an action and read them with useActionData; throw unexpected ones so an error element renders.
  • useNavigation gives the pending state (idle, submitting, loading) and navigation.formData the values that were sent.
  • useFetcher runs an action without navigating. Each fetcher has its own state, which makes concurrent inline mutations and optimistic updates simple.
  • Derive optimistic UI from fetcher.formData and rollback needs no code.
  • Put errorElement on the smallest route that makes sense, and use a pathless route to keep layouts visible.

Next: Project: A Product Catalog with Filters and a Cart