Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 50 ยท Data Mode

Actions and Form

Handle form submissions with React Router actions: the Form component, request.formData(), validation with useActionData, redirect after submit and automatic revalidation.

Loaders bring data into a page. Actions are their counterpart for sending changes back: creating a note, renaming a project, deleting an item. An action is a function you attach to a route. You trigger it by submitting a form, the router runs the function, and when it finishes the router automatically reloads the page's data so the screen shows the new truth.

This is a different mental model from the usual React form, where you write an onSubmit handler, call fetch, store the response in state, and manually refresh whatever list changed. With actions, the form just describes what is being submitted and where. The router handles the rest: pending state, errors, redirects and refreshing the page's data. In this lesson you will write an action, use the <Form> component, validate input, redirect after success, and see the automatic revalidation in a runnable stand-in.

If you are not sure how HTML forms work, read Forms and Inputs and Form Actions first. You also need a data router (see createBrowserRouter and RouterProvider).

Your first action

Here is the real React Router API, shown read-only:

JSX
// Real React Router (data mode), read-only
import { createBrowserRouter, Form, redirect, useLoaderData } from 'react-router';

async function notesLoader() {
  const response = await fetch('/api/notes');
  return response.json();
}

async function createNoteAction({ request }) {
  const formData = await request.formData();
  const title = String(formData.get('title') ?? '').trim();

  const response = await fetch('/api/notes', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title }),
  });
  const note = await response.json();
  return redirect('/notes/' + note.id);
}

function Notes() {
  const notes = useLoaderData();
  return (
    <div>
      <ul>
        {notes.map((n) => <li key={n.id}>{n.title}</li>)}
      </ul>
      <Form method="post">
        <input name="title" />
        <button type="submit">Add note</button>
      </Form>
    </div>
  );
}

const router = createBrowserRouter([
  { path: '/', Component: Notes, loader: notesLoader, action: createNoteAction },
  { path: '/notes/:id', Component: NotePage, loader: noteLoader },
]);

When the user presses Add note, this happens:

  1. <Form> stops the browser's normal submission (which would reload the page).
  2. The router builds a Request from the form and calls the route's action with it.
  3. The action reads the data, performs the change and returns something (here, a redirect).
  4. The router acts on the result and then re-runs loaders so the page is up to date.
sequenceDiagram
  participant U as User
  participant F as Form
  participant R as Router
  participant A as Action
  participant L as Loaders
  U->>F: presses Add note
  F->>R: submit POST to this route
  R->>A: call action with request
  A-->>R: result, such as a redirect
  R->>L: revalidate loaders
  L-->>R: fresh data
  R-->>U: render the page

After an action finishes, the router reloads the data that is on screen, so you never refresh lists by hand.

The action function

An action receives the same { params, request } object as a loader. What is different is request: it carries the submitted form.

  • request.method is 'POST', 'PUT', 'PATCH' or 'DELETE' (always upper case), taken from the method prop of <Form>.
  • await request.formData() gives you a standard FormData object with every field that has a name. Read single values with formData.get('title'), several with formData.getAll('tags'), or convert everything with Object.fromEntries(formData).
  • params has the route's dynamic segments, for example params.id in an action on /notes/:id.

Fields come out of FormData as strings (or File objects), so convert and validate them: Number(formData.get('price')), formData.get('agree') === 'on' for a checkbox. Never trust them just because the browser form had required; anyone can send any request.

An action can end in three ways, much like a loader:

flowchart TD
  A["Action finishes"] --> Q{"What did it do?"}
  Q -- "returned redirect(...)" --> N["Navigate to the new URL, then load its data"]
  Q -- "returned data" --> D["Stay on the page, expose data with useActionData, revalidate loaders"]
  Q -- "threw an error or Response" --> E["Render the nearest error element"]

A redirect moves the user on, returned data keeps them on the form, and a throw ends in an error boundary.

Validation with useActionData

For expected problems, such as an empty title, return data instead of throwing. The component reads it with useActionData, which is undefined until the form has been submitted.

JSX
// Real React Router, read-only
import { Form, useActionData } from 'react-router';

async function createNoteAction({ request }) {
  const formData = await request.formData();
  const title = String(formData.get('title') ?? '').trim();

  if (title === '') {
    return { error: 'A note needs a title.' };
  }
  if (title.length > 80) {
    return { error: 'Keep the title under 80 characters.' };
  }

  const note = await saveNote({ title });
  return redirect('/notes/' + note.id);
}

function NewNote() {
  const actionData = useActionData();
  return (
    <Form method="post">
      <input name="title" aria-invalid={Boolean(actionData?.error)} />
      {actionData?.error && <p role="alert">{actionData.error}</p>}
      <button type="submit">Add note</button>
    </Form>
  );
}

Return validation results; throw only for the things you did not expect (a network failure, a 500 from the server). That keeps your error pages for real emergencies, and your forms friendly. Add a status with data({ error }, { status: 400 }) if the response should carry one, which matters in framework mode. Also remember that client-side validation is a convenience, not security. The server behind your API has to repeat every check (see Form Validation).

Redirect after action

After a successful change, return redirect(url). This is the Post/Redirect/Get pattern from classic web development, and it matters for three reasons:

  • The user lands on a normal page with a normal URL, so pressing reload does not submit the form a second time.
  • The URL is shareable and bookmarkable.
  • The loaders of the new page run, so it shows fresh data.

Redirects also work for other cases, such as sending the user to a list after a delete. If an action does not redirect and returns data (or nothing), the user stays on the same page and its loaders are revalidated.

Where does the form submit to?

By default, <Form> submits to the route that renders it (technically, the closest route in the tree). That is why the example above needed no action attribute. You can point a form at another route:

JSX
// Real React Router, read-only
<Form method="post" action="/notes/42">
  <input type="hidden" name="intent" value="delete" />
  <button type="submit">Delete</button>
</Form>

Relative action values resolve like relative links. One special case: when a layout route and its index route share the same URL, both could handle the form. Use action="?index" to address the index route's action. Most beginners never meet this, but if "my action is not called" and you have a layout around the page, check it.

Several forms, one action: the intent pattern

A route has one action, but a page often has several buttons that mean different things. A common solution is an intent field in the form data and a switch in the action:

JSX
// Real React Router, read-only
async function noteAction({ request, params }) {
  const formData = await request.formData();
  const intent = formData.get('intent');

  switch (intent) {
    case 'rename': {
      const title = String(formData.get('title') ?? '').trim();
      if (title === '') {
        return { error: 'The title cannot be empty.' };
      }
      await renameNote(params.id, title);
      return { saved: true };
    }
    case 'delete': {
      await deleteNote(params.id);
      return redirect('/');
    }
    default:
      throw new Response('Unknown intent', { status: 400 });
  }
}

The two forms can be separate <Form> elements with a hidden intent input, or one form with two buttons that each have name="intent" and a different value. The pressed button's name and value are sent with the form.

Try it: actions and revalidation

The stand-in below is a miniature data router with loaders and actions. A fake in-memory "database" holds notes. The list page's action creates a note (returning a validation error when the title is empty, or a redirect to the new note when it works). The note page's action uses the intent pattern to rename or delete. The <Form> component builds FormData from the submitted form and calls router.submit, and the action code reads it with await request.formData(), exactly as in the real library.

Look at the log under the page after each submission: it shows which action ran and which loaders were revalidated afterwards. Try an empty title first, then add a note, rename it, and delete it.

A tiny router with loaders, actions and a Form

Submitting an empty title ends with action returned {"error":"A note needs a title."} followed by a revalidation of the list loader: the page stays on the list and shows the error. A valid title ends with action redirected to /notes/3, and the new note's page appears with its own loader's data. The rename form returns {"saved":true} and the page shows "Saved." while the heading changes, because the note's loader ran again after the action. Delete redirects back to the list, where the note is gone.

What is real and what is stand-in? The loaders, the actions, the redirect use, request.formData() and the way components read data are the same code you would write with React Router. The router itself, Form, RouterProvider and the log are the stand-in. The real router also handles concurrent submissions, error boundaries, useNavigation, the ?index rule and many more details.

GET forms: search without an action

A form with method="get" is different. It does not call an action. <Form method="get"> navigates to the same route with the form fields as the query string, which makes the route's loader run again with a new request.url. This is the ideal way to build a search box or a filter:

JSX
// Real React Router, read-only
<Form method="get">
  <input name="q" defaultValue={query} />
  <button type="submit">Search</button>
</Form>

The result is a shareable URL such as /products?q=monitor, and the browser's back button steps through earlier searches. See Search Params and Putting UI State in the URL for the pattern in depth.

Common mistakes

  • Using a lowercase <form> and expecting the router to handle it. Only <Form> is wired to actions; a plain <form> triggers a normal browser submission.
  • Forgetting name on inputs. Fields without a name are not part of FormData, so formData.get('title') returns null.
  • Returning a redirect for validation errors. Redirecting loses what the user typed. Return the error data instead.
  • Putting secrets in an action. In data mode actions run in the browser. Anything a user can submit needs server-side authorization, as explained in Protected Routes.
  • Doing the refresh yourself. After an action, do not call fetch again or keep a copy of the list in state. Let the router revalidate, and read the data with useLoaderData.

For updates that should not navigate or reload the whole page, such as a "like" button, use a fetcher: useFetcher and Inline Mutations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does an action read the submitted fields?

    The action receives a Request. Its formData() method returns a FormData object with every named field.
  2. 2. After an action finishes without redirecting, what does the router do?

    Automatic revalidation is one of the main benefits of actions: after a submission, active loaders run again and the UI updates itself.
  3. 3. What should an action do when the title field is empty?

    Expected validation problems are returned as data. The form stays on screen with the user's input, and the component displays the message.
  4. 4. Why return redirect('/notes/3') after creating a note?

    Post/Redirect/Get avoids duplicate submissions, gives the result a real URL and loads the destination's data.
  5. 5. A route needs separate rename and delete buttons on one page. What is a common way to handle this with one action?

    A route has a single action. An intent field (hidden input, or a button with name and value) tells the action which operation was requested.

Summary

  • An action is a function on a route that handles submissions; <Form> sends a request to it without a full page reload.
  • Read fields with await request.formData(), and request.method, params for the rest of the request.
  • Return data for validation errors and read it with useActionData. Return redirect(...) after success, and throw only for unexpected failures.
  • After an action, the router automatically revalidates loaders, so you do not refresh lists by hand.
  • Use an intent field to run several operations from one route's action, and <Form method="get"> for search and filters.
  • The runnable example is a stand-in router; the loader, action and component code in it is what you would write with the real library.

Next: useFetcher and Inline Mutations