Skip to content

React forms and routing: actions, validation, Router

Forms and navigation are where a React app meets real users and real servers: data must be validated, saved, shown as pending and then reflected in the URL and the next screen. This page covers controlled and uncontrolled inputs, React 19 form actions, schema validation with React Hook Form and Zod, and client routing with React Router 8. The examples follow an OrdersPortal customer through applying a discount code, changing a shipping address, requesting a return and cancelling an order.

The samples target React 19.3, React Hook Form 7.92, Zod 4.6 and React Router 8.5. Each was bundled with esbuild, rendered into a jsdom document in Node.js 22 and driven by the short driver at the end of the sample, which types into fields and submits forms; the printed output is shown below each.

Topic Use it when
Controlled and uncontrolled inputs You decide who owns an input’s value: React state or the DOM.
Form actions A form submits to an async function and shows pending, error and success states.
Form libraries A form has many fields, schema validation and field-level errors.
Routing with React Router Screens map to URLs and load or change data on navigation.

A controlled input gets its value from state and reports every keystroke through onChange; React is the single source of truth, so you can normalize, limit or validate as the user types and derive UI such as an enabled button from the value. An uncontrolled input keeps its own value in the DOM; you set the starting value with defaultValue and read the final value on submit, usually from FormData. Uncontrolled inputs need less code and fewer re-renders, which is why form actions and React Hook Form use them.

Pick controlled when the UI must react to each keystroke (formatting, instant feedback, dependent fields) and uncontrolled when you only need the values on submit. Do not switch one input between the two: passing value={undefined} and later a string makes React warn, so initialize controlled state with ''.

import { useState } from 'react';
function DiscountCodeField({ onApply }) {
const [code, setCode] = useState('');
const normalized = code.trim().toUpperCase();
const isValid = /^[A-Z]{4}-\d{2}$/.test(normalized); // derived, not stored
return (
<form onSubmit={(event) => { event.preventDefault(); onApply(normalized); }}>
<input
aria-label="Discount code"
value={code} // controlled: React owns the value
onChange={(event) => setCode(event.target.value.slice(0, 7))}
/>
<button disabled={!isValid}>Apply</button>
<small>{code === '' ? 'Format: ABCD-12' : isValid ? 'Looks good' : 'Format: ABCD-12'}</small>
</form>
);
}
// Driver: type into the input the way a browser would.
import { act } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
await act(() => root.render(<DiscountCodeField onApply={(c) => console.log(`applied ${c}`)} />));
const input = document.querySelector('input');
const setNativeValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
async function type(text) {
await act(() => { setNativeValue.call(input, text); input.dispatchEvent(new Event('input', { bubbles: true })); });
console.log(`"${input.value}" -> ${document.querySelector('small').textContent}, button enabled: ${!document.querySelector('button').disabled}`);
}
await type('save-1');
await type('save-10-extra');
await act(() => document.querySelector('button').click());

Output:

"save-1" -> Format: ABCD-12, button enabled: false
"save-10" -> Looks good, button enabled: true
applied SAVE-10

The onChange handler trims input to seven characters, so the user cannot type past the code length; validity is derived from the value on every render rather than stored.

Pitfalls:

  • value without onChange makes a read-only field; React warns. Use defaultValue for an uncontrolled field or readOnly on purpose.
  • Controlled inputs for large forms re-render the form on every keystroke; with dozens of fields prefer uncontrolled inputs and a form library.
  • Forgetting preventDefault() in an onSubmit handler lets the browser do a full-page submit.

React 19 lets you pass a function to a form’s action prop. On submit React calls it with the form’s FormData, inside a transition, so the UI stays responsive. useActionState(action, initialState) wraps that function so it also receives the previous state and returns the next one, typically errors or a success flag, and gives you an isPending flag. useFormStatus() from react-dom lets a child such as a submit button read the pending state of the form it is in, without prop drilling. useOptimistic can show the expected result immediately while the action runs.

After an action completes without throwing, React resets the form’s uncontrolled fields. That is right for “add another” forms, but for edit forms or validation errors you want to keep what the user typed, so the sample returns the submitted values in the state and uses them as defaultValues. With a framework that supports React Server Components, the same action can be a server function marked 'use server', and the form works before JavaScript loads.

import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
// A server call stand-in: rejects one postal code, succeeds otherwise.
async function saveAddress(orderId, address) {
await new Promise((r) => setTimeout(r, 10));
if (address.postalCode === '00000') return { ok: false, error: 'Postal code is not deliverable' };
return { ok: true };
}
function SubmitButton() {
const { pending } = useFormStatus(); // reads the parent form's status
return <button type="submit" disabled={pending}>{pending ? 'Saving...' : 'Save address'}</button>;
}
function ShippingAddressForm({ orderId }) {
const [state, formAction, isPending] = useActionState(async (previous, formData) => {
const address = { street: formData.get('street').trim(), postalCode: formData.get('postalCode').trim() };
if (!address.street) return { error: 'Street is required', values: address };
const result = await saveAddress(orderId, address);
return result.ok ? { saved: true, values: address } : { error: result.error, values: address };
}, { values: { street: '', postalCode: '' } });
return (
<form action={formAction}>
<input name="street" defaultValue={state.values.street} aria-label="Street" />
<input name="postalCode" defaultValue={state.values.postalCode} aria-label="Postal code" />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
{state.saved && <p role="status">Address saved for order {orderId}</p>}
</form>
);
}
// Driver: fill the fields, submit, wait for the action.
import { act } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
await act(() => root.render(<ShippingAddressForm orderId={1001} />));
async function submit(street, postalCode) {
const form = document.querySelector('form');
form.elements.street.value = street;
form.elements.postalCode.value = postalCode;
await act(async () => { form.requestSubmit(); await new Promise((r) => setTimeout(r, 30)); });
console.log(document.querySelector('[role]')?.textContent);
}
await submit('', '1011 AB');
await submit('Main Street 5', '00000');
await submit('Main Street 5', '1011 AB');

Output:

Street is required
Postal code is not deliverable
Address saved for order 1001

Pitfalls:

  • Lost input on error. Without returning and re-applying the submitted values, a validation error clears the fields.
  • useFormStatus in the same component as the form reads the status of a parent form, not this one; put it in a child component, as SubmitButton does.
  • Client checks only. Validation in the action improves the experience, but the server must validate again.

For larger forms, React Hook Form (version 7) manages registration, dirty and touched tracking, field-level errors and submission state with uncontrolled inputs, so typing does not re-render the whole form. register('email') returns the name, ref, onChange and onBlur props for an input; handleSubmit(onValid) validates and calls your function only with valid data; formState.errors holds messages per field. useFieldArray handles repeating groups such as order lines.

Pair it with a schema library through @hookform/resolvers. With Zod 4 you describe the shape once, get coercion (the order number arrives from the input as a string and z.coerce.number() converts it), share the schema with the server for the same rules on both sides, and infer a TypeScript type with z.infer<typeof ReturnRequest>. Zod 4 moved string formats to top-level helpers such as z.email() and uses an error option for custom messages.

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
const ReturnRequest = z.object({
orderId: z.coerce.number().int().positive('Enter an order number'),
email: z.email('Enter a valid email'),
reason: z.enum(['damaged', 'wrong-item', 'no-longer-needed'], { error: 'Choose a reason' }),
details: z.string().max(200).optional(),
});
function ReturnRequestForm({ onSubmit }) {
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm({
resolver: zodResolver(ReturnRequest),
defaultValues: { orderId: '', email: '', reason: '', details: '' },
});
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<input aria-label="Order number" {...register('orderId')} />
{errors.orderId && <p className="error">{errors.orderId.message}</p>}
<input aria-label="Email" type="email" {...register('email')} />
{errors.email && <p className="error">{errors.email.message}</p>}
<select aria-label="Reason" {...register('reason')}>
<option value="">Choose...</option>
<option value="damaged">Damaged</option>
<option value="wrong-item">Wrong item</option>
<option value="no-longer-needed">No longer needed</option>
</select>
{errors.reason && <p className="error">{errors.reason.message}</p>}
<textarea aria-label="Details" {...register('details')} />
<button disabled={isSubmitting}>Request return</button>
</form>
);
}
// Driver
import { act } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
await act(() => root.render(<ReturnRequestForm onSubmit={(data) => console.log('submitted', JSON.stringify(data))} />));
const form = document.querySelector('form');
const submit = async () => {
await act(async () => { form.requestSubmit(); await new Promise((r) => setTimeout(r, 20)); });
console.log([...document.querySelectorAll('.error')].map((p) => p.textContent));
};
await submit();
const fill = (index, value) => {
const element = form.elements[index];
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), 'value').set.call(element, value);
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
};
await act(() => { fill(0, '1001'); fill(1, 'ada@example.test'); fill(2, 'damaged'); });
await submit();

Output:

[ 'Enter an order number', 'Enter a valid email', 'Choose a reason' ]
submitted {"orderId":1001,"email":"ada@example.test","reason":"damaged","details":""}
[]

Pitfalls:

  • Zod 3 examples on Zod 4. z.string().email() still works but is deprecated; required_error and invalid_type_error were replaced by error.
  • Numbers from inputs are strings. Use z.coerce.number() or register('qty', { valueAsNumber: true }).
  • watch() at the top of a big form re-renders the form on every change; use useWatch in the component that needs the value.

React Router is the most widely used router for React apps that are not built on a meta-framework. Version 8 (June 2026) requires React 19.2.7 or later and Node.js 22.22 or later for its tooling, ships ESM only, and removed the old react-router-dom package: import everything from react-router, and RouterProvider for the browser from react-router/dom. It has three modes: declarative (<BrowserRouter> with <Routes> and <Route>), data (createBrowserRouter with route objects that add loader, action and error boundaries) and framework (a Vite plugin with file-based routes, server rendering and type generation).

In data mode, each route’s loader runs before the route renders and its result is read with useLoaderData(); an action handles <Form method="post"> submissions and usually returns redirect(), after which React Router reloads the data for the new page. Throwing data(message, { status: 404 }) from a loader renders the nearest errorElement. useNavigation() exposes pending state for a global loading indicator, <Outlet /> renders child routes inside a layout, and useParams, useSearchParams and useNavigate cover parameters, query strings and programmatic navigation.

import { Form, Link, Outlet, data, isRouteErrorResponse, redirect, useLoaderData, useNavigation, useRouteError } from 'react-router';
// In-memory "API" for the sample.
const orders = new Map([[1001, { id: 1001, customer: 'Ada Lopez', status: 'open' }], [1002, { id: 1002, customer: 'Ben Ortiz', status: 'shipped' }]]);
function Layout() {
const navigation = useNavigation();
return (
<div>
<nav><Link to="/orders">Orders</Link></nav>
{navigation.state !== 'idle' && <p>Loading...</p>}
<main><Outlet /></main>
</div>
);
}
function OrderList() {
const { list } = useLoaderData();
return <ul>{list.map((o) => <li key={o.id}><Link to={`/orders/${o.id}`}>Order {o.id}</Link> {o.status}</li>)}</ul>;
}
function OrderDetail() {
const { order } = useLoaderData();
return (
<section>
<h1>Order {order.id}: {order.status}</h1>
{order.status === 'open' && (
<Form method="post" action="cancel"><button>Cancel order</button></Form>
)}
</section>
);
}
function OrderError() {
const error = useRouteError();
return <p role="alert">{isRouteErrorResponse(error) ? `${error.status}: ${error.data}` : 'Something went wrong'}</p>;
}
export const routes = [
{
path: '/',
element: <Layout />,
hydrateFallbackElement: <p>Loading...</p>,
children: [
{ index: true, loader: () => redirect('/orders') },
{ path: 'orders', element: <OrderList />, loader: async () => ({ list: [...orders.values()] }) },
{
path: 'orders/:orderId',
element: <OrderDetail />,
errorElement: <OrderError />,
loader: async ({ params }) => {
const order = orders.get(Number(params.orderId));
if (!order) throw data(`Order ${params.orderId} not found`, { status: 404 });
return { order };
},
},
{
path: 'orders/:orderId/cancel',
action: async ({ params }) => {
orders.get(Number(params.orderId)).status = 'cancelled';
return redirect(`/orders/${params.orderId}`);
},
},
],
},
];
// In the app: const router = createBrowserRouter(routes);
// createRoot(el).render(<RouterProvider router={router} />); // RouterProvider from 'react-router/dom'
// Driver: a memory router in jsdom.
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { createMemoryRouter, RouterProvider } from 'react-router';
const router = createMemoryRouter(routes, { initialEntries: ['/'] });
const root = createRoot(document.getElementById('root'));
const settle = () => act(() => new Promise((r) => setTimeout(r, 20)));
const show = () => console.log(`${router.state.location.pathname} | ${[...document.querySelectorAll('main li, main h1, main p, main button')].map((e) => e.textContent).join(' / ')}`);
await act(() => root.render(<RouterProvider router={router} />)); await settle(); show();
await act(() => document.querySelector('main a').click()); await settle(); show();
await act(() => document.querySelector('form button').click()); await settle(); show();
await act(() => router.navigate('/orders/9999')); await settle(); show();

Output:

/orders | Order 1001 open / Order 1002 shipped
/orders/1001 | Order 1001: open / Cancel order
/orders/1001 | Order 1001: cancelled
/orders/9999 | 404: Order 9999 not found

For a protected area, add a parent route whose loader checks the session and throws redirect('/login'), or, in framework mode, middleware; in declarative mode the equivalent is a layout component that renders <Navigate to="/login" replace /> when there is no user.

Pitfalls:

  • v6 imports after upgrading. react-router-dom no longer exists in v8; replace the imports as the upgrade guide describes.
  • Fetching in effects inside routed screens. Loaders start requests in parallel with code loading and avoid request waterfalls; prefer them in data mode.
  • Server hosting. Client routes need the server to return index.html for unknown paths, otherwise refreshing /orders/1001 gives a 404.
Situation Choose
One or two fields with live formatting Controlled inputs with useState
Simple submit-and-save form, or a framework with server functions Form action with useActionState
Many fields, field-level errors, shared schema with the API React Hook Form with Zod
Client-side app with a few screens React Router declarative mode
Screens that load and mutate data React Router data mode (or framework mode for server rendering)

When do you choose a controlled input over an uncontrolled one? When the UI depends on each keystroke: formatting, live validation, enabling buttons, dependent fields. If you only need the final value on submit, uncontrolled inputs read through FormData are simpler and render less.

What does useActionState return, and what does React do around the action? The current state, a wrapped action to pass to the form, and an isPending flag. React runs the action in a transition, passes the previous state and the FormData, updates the state with the return value, and resets uncontrolled fields after success.

Why share a Zod schema between the browser and the API? One definition gives the same rules and messages on both sides, a TypeScript type for free and no drift. The client copy improves the experience; the server copy is the one that protects the data.

What is the difference between a loader and fetching in useEffect? A loader runs on navigation before the route renders, in parallel for nested routes, and its errors go to route error boundaries. An effect runs after render, so nested components fetch one after another and must handle races, loading and errors themselves.

Senior scenario: an order edit form sometimes saves stale data when users double-click Save or edit in two tabs. How do you fix it? Disable the submit button while the action is pending (useFormStatus), and make the server authoritative: send a version or updatedAt with the edit and reject mismatches with 409 Conflict, then show the latest data and let the user merge. Use an idempotency key for the submit so a retried request does not apply twice.