Course contentsShow
← React
Lesson 1848 of 2,39643. RoutingFree lesson

Route Actions for Mutations

Defining action functions to handle form submissions and mutations declaratively.

Route Actions for Mutations

What you'll learn: How to handle form submissions and data mutations declaratively using route-level action functions in React Router's data router paradigm.

The Declarative Way to Mutate Data

Just as loaders let you fetch data before rendering, actions let you handle mutations (create, update, delete operations) at the route level. When a form submits to a route with an action, React Router intercepts the submission, calls your action function, and automatically revalidates all loaders on the page—giving you declarative data flow in both directions.

Think of it like this: loaders are "read" operations at route boundaries, and actions are "write" operations. Instead of manually calling mutation functions from event handlers, you let the route handle it.

Defining an Action Function

Actions work just like loaders—they're functions you attach to route definitions:

const router = createBrowserRouter([
  {
    path: "/tasks/:id",
    element: <TaskDetail />,
    loader: taskLoader,
    action: taskAction, // Handles mutations
  }
]);

async function taskAction({ request, params }) {
  const formData = await request.formData();
  const updates = Object.fromEntries(formData);
  
  await updateTask(params.id, updates);
  
  return { success: true };
}

When a <Form> (React Router's enhanced form component) submits to this route, taskAction runs automatically. The action receives the form submission as a request object and route parameters.

After the action completes, React Router automatically calls all active loaders to refresh the page data—no manual cache invalidation needed.

Key Takeaway: Route actions provide a declarative pattern for handling mutations at the route level, with automatic revalidation of loaders, making data mutations as elegant as data fetching in the data router paradigm.