Submit route actions and fetchers
Use an action for a route mutation
A route action processes a mutation initiated by a router form or submission API. A Form with method="post" targets an action, unlike a GET form that changes URL search parameters. In our client-only fixture an action modifies an in-memory reservation list, not a database; data disappears on page reload. Validate the input before changing the list. Real authentication, authorization, CSRF protections as applicable and persistence belong to a reviewed server integration. A client action cannot enforce them.
import React from 'react';import { createMemoryRouter, Form, useActionData, useLoaderData, useNavigation } from 'react-router';import { RouterProvider } from 'react-router/dom';let reservations = [];function validateTitle(value) { if (typeof value !== 'string') return {error:'Enter a book title.'}; const title = value.trim(); if (!title || title.length > 60) return {error:'Use 1–60 characters.'}; return {title};}async function action({request}) { const input = validateTitle((await request.formData()).get('title')); if (input.error) return input; reservations = [...reservations, {id:reservations.length+1, title:input.title}]; return {ok:true};}function Reservations() { const items = useLoaderData(); const result = useActionData(); const navigation = useNavigation(); return <main><h1>Reservations</h1><Form method="post"><label>Book <input name="title" /></label> <button disabled={navigation.state !== 'idle'}>Reserve</button></Form> <p role="status">{result?.error || (result?.ok ? 'Reserved locally.' : '')}</p> <ul>{items.map(item => <li key={item.id}>{item.title}</li>)}</ul></main>;}const router = createMemoryRouter([{path:'/',loader:()=>reservations,action,Component:Reservations}]);export default function App() { return <RouterProvider router={router} />; }Submitting whitespace returns a validation message; submitting Pocket Atlas should add a row. In normal successful action flows the router revalidates applicable loader data, so the list can reflect the mutation without an additional Effect. Revalidation rules vary by version, response status and route configuration; do not assume every loader always reruns. This example does not model concurrent durable writes or deduplication.
Redirect after a completed action
import React from 'react';import { createMemoryRouter, Form, redirect, Link } from 'react-router';import { RouterProvider } from 'react-router/dom';const router = createMemoryRouter([ {path:'/', element:<main><h1>Reserve a reading slot</h1><Form method="post"><button>Confirm demo slot</button></Form></main>, action:()=>redirect('/confirmed')}, {path:'/confirmed', element:<main><h1>Demo confirmation</h1><Link to="/">Back</Link></main>}]);export default function App() { return <RouterProvider router={router} />; }Confirm demo slot should navigate to /confirmed. This demonstrates redirect control flow only; no slot is stored. In a real mutation, redirect only after the required work succeeds. Keep redirect destinations trusted or validated; do not redirect to arbitrary untrusted user input. A redirect from a fetcher can also cause navigation.
Use a fetcher when the page should stay in place
import React from 'react';import { createMemoryRouter, useFetcher } from 'react-router';import { RouterProvider } from 'react-router/dom';function copiesFor(id) { return id === 'atlas' ? 2 : id === 'garden' ? 0 : null; }function Availability() { const fetcher = useFetcher(); return <main><h1>Check copies</h1><fetcher.Form method="post"><label>Book <select name="id"><option value="atlas">Pocket Atlas</option><option value="garden">City Gardens</option></select></label> <button disabled={fetcher.state !== 'idle'}>Check</button></fetcher.Form> <p role="status">{fetcher.state !== 'idle' ? 'Checking…' : fetcher.data?.message || ''}</p></main>;}const router = createMemoryRouter([{path:'/',Component:Availability,action:async ({request})=>{ const count = copiesFor((await request.formData()).get('id')); return {message:count === null ? 'Unknown book.' : `${count} copies available.`};}}]);export default function App() { return <RouterProvider router={router} />; }Pocket Atlas should report 2 copies available; City Gardens should report 0 copies available. The location normally stays unchanged because a fetcher submission is not a navigation, unless a response redirects. This read-only demo deliberately exercises a POST action; for real read-only lookups use fetcher.load or a GET fetcher form and a loader. Each fetcher has its own pending state and returned data. useRevalidator can request revalidation for an external event; avoid manually triggering a duplicate reload after every action. Use one authoritative route dataset rather than separately mutating a client query cache without a synchronization strategy.
Practice
Extend the title validator to reject duplicates by an explicit policy and describe how the server would enforce it atomically. Test whitespace, long input and a valid title. Compare the navigation history for Form and fetcher.Form.