React · Lesson 6
Forms & data
Controlled and uncontrolled inputs, validation with typed errors, React 19 actions (useActionState, useFormStatus, useOptimistic), server state vs client state, a query cache like TanStack Query, and optimistic updates with rollback.
In short
- Controlled: React state; uncontrolled: the DOM
- Start inputs with
'', neverundefined - Validate into typed codes; the server validates too
- Actions:
useActionStateanduseFormStatus - Server data lives in a query cache with good keys
Most screens in a business app are a form or a list of data from an API, often both. The React side of that work comes down to two questions: who owns the value in an input (React state or the DOM), and who owns the data from the server (your component, or a cache). Get those right and most of the code becomes simple; get them wrong and you spend your time syncing copies of the same data.
React can't run in the lab, so React snippets have no ▶ Try button. Plain TypeScript snippets do, and the
exercises rebuild the mechanisms: parsing FormData, typed validation, a form state machine, query keys, the action
queue behind useActionState, a query cache and an optimistic store.
Controlled and uncontrolled inputs
A controlled input gets its value from React state, and every keystroke goes through your onChange:
import { useState } from 'react';
export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('');
return (
<form onSubmit={(e) => { e.preventDefault(); onSearch(query.trim()); }}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button disabled={query.trim() === ''}>Search</button>
</form>
);
}
An uncontrolled input keeps its own value in the DOM. You give it a starting value with defaultValue (or
defaultChecked) and read it when you need it, usually from the form's FormData on submit:
// (not runnable here)
export function NewsletterForm({ subscribe }: { subscribe: (email: string) => Promise<void> }) {
return (
<form
onSubmit={async (e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
await subscribe(String(data.get('email') ?? ''));
}}
>
<input name="email" type="email" defaultValue="" required />
<button>Subscribe</button>
</form>
);
}
| Controlled | Uncontrolled | |
|---|---|---|
| Source of truth | React state | The DOM |
| Re-renders | On every keystroke | None while typing |
| Good for | Live validation, formatting, fields that depend on each other, disabling a button as you type | Simple forms, React 19 form actions, large forms (React Hook Form uses refs) |
| Reset | Set the state | form.reset(), or change the form's key |
Things that trip people up:
value={undefined}makes an input uncontrolled. If the state starts asundefinedand later becomes a string, React warns that "a component is changing an uncontrolled input to be controlled". Start with'', or writevalue={name ?? ''}.valuewithoutonChangeis read-only. React keeps putting the old value back.- Checkboxes use
checked, notvalue, and reade.target.checked. - Everything except a file is a string.
<input type="number">gives"42", and so doesFormData. An unchecked checkbox isn't inFormDataat all, and a checkbox group sends one entry per checked box:
// What a browser submits for: name "Ann", the newsletter box unchecked, the React and Cloud topic boxes checked.
const form = new URLSearchParams('name=Ann&topics=react&topics=cloud');
console.log(form.get('name')); // Ann
console.log(form.get('newsletter')); // null: unchecked boxes aren't sent
console.log(form.get('topics')); // react: get() only returns the first
console.log(form.getAll('topics')); // all of them
- React's
onChangefires on every input (like the DOM'sinputevent), not when the field loses focus.
Exercise 1 parses a FormData into a typed object.
Validation with typed errors
Validate into error codes, typed per field, and turn codes into messages in one place:
type SignupErrors = {
email?: 'required' | 'invalid';
password?: 'required' | 'tooShort';
};
function validate(values: { email: string; password: string }): SignupErrors {
const errors: SignupErrors = {};
if (values.email.trim() === '') errors.email = 'required';
else if (!values.email.includes('@')) errors.email = 'invalid';
if (values.password === '') errors.password = 'required';
else if (values.password.length < 8) errors.password = 'tooShort';
return errors;
}
console.log(validate({ email: 'ann.example.com', password: 'secret' }));
console.log(validate({ email: '', password: 'correct horse' }));
- Codes are easy to test, translate and match on, and a mapped type can force a message for every code (exercise 2).
- Validate always, show selectively: an error appears once the field is touched (blurred) or the user tried to submit. Exercise 3 builds that state machine (touched, dirty, submitting, server errors).
- Connect errors to inputs for screen readers:
aria-invalidon the input andaria-describedbypointing at the message. - The server validates too. Client checks are for speed. An ASP.NET Core API answers with a
ValidationProblemDetailsbody,{ "title": "...", "status": 400, "errors": { "Email": ["..."] } }, which a small adapter maps to your field errors:
type ValidationProblem = { title: string; status: number; errors?: Record<string, string[]> };
function toFieldErrors(problem: ValidationProblem): Record<string, string> {
const out: Record<string, string> = {};
for (const [field, messages] of Object.entries(problem.errors ?? {})) {
out[field.charAt(0).toLowerCase() + field.slice(1)] = messages[0]; // "Email" -> "email"
}
return out;
}
console.log(toFieldErrors({ title: 'One or more validation errors occurred.', status: 400, errors: { Email: ['Already registered.'] } }));
Schema libraries describe the rules once and give you the type for free:
import { z } from 'zod';
const Signup = z.object({
email: z.email(),
age: z.coerce.number().int().min(18).optional(),
});
type Signup = z.infer<typeof Signup>; // { email: string; age?: number | undefined }
const result = Signup.safeParse(Object.fromEntries(formData));
if (!result.success) console.log(result.error.issues); // path + message per problem
Form libraries put it together: React Hook Form (uncontrolled inputs through refs, so typing doesn't re-render the form), TanStack Form, and Formik in older code.
React 19 actions
React 19 adds actions: async functions that React runs in a transition, with pending state, errors and
optimistic updates built in. The simplest is a function passed to a form's action prop. It receives the
FormData, and when it succeeds React resets the form's uncontrolled fields:
import { useActionState, useOptimistic, useRef } from 'react';
import { useFormStatus } from 'react-dom';
import { postComment, type Comment } from './api';
type State = { comments: Comment[]; error: string | null };
function SubmitButton() {
const { pending } = useFormStatus(); // the status of the <form> this component is inside
return <button disabled={pending}>{pending ? 'Posting...' : 'Post'}</button>;
}
export function Comments({ initial }: { initial: Comment[] }) {
const [state, formAction, isPending] = useActionState(
async (previous: State, formData: FormData): Promise<State> => {
const text = String(formData.get('text') ?? '').trim();
if (text === '') return { ...previous, error: 'Write something first.' }; // a known error: returned as state
addOptimistic(text);
const saved = await postComment(text); // an unknown error (a 500) throws: the nearest error boundary shows it
return { comments: [...previous.comments, saved], error: null };
},
{ comments: initial, error: null },
);
const [optimistic, addOptimistic] = useOptimistic(state.comments, (list: Comment[], text: string) => [
...list,
{ id: `pending-${list.length}`, text, sending: true },
]);
return (
<form action={formAction}>
<ul>{optimistic.map((c) => <li key={c.id} style={{ opacity: c.sending ? 0.5 : 1 }}>{c.text}</li>)}</ul>
<textarea name="text" />
{state.error && <p role="alert">{state.error}</p>}
<SubmitButton />
{isPending && <small>Saving...</small>}
</form>
);
}
useActionState(action, initialState)returns[state, dispatchAction, isPending]. The action receives the previous state and the payload (theFormDatawhen used as a form action). Because of that, React runs dispatched actions one at a time, in order, and if one throws, React cancels the ones still queued and shows the nearest error boundary. Return expected problems as state; throw only for the unexpected. Exercise 5 builds the queue.useFormStatus()comes fromreact-domand must be called in a component inside the<form>. It givespending,data,methodandactionfor that form.useOptimistic(value, reducer?)returns a value that shows optimistic changes while an action is running and falls back tovaluewhen it ends. Call its setter inside an action orstartTransition; outside one, the change flashes and disappears. Exercise 7 builds the replay-on-top model behind it.- To dispatch outside a form, call
startTransition(() => dispatchAction(payload)). - With a framework such as Next.js, an action can be a server function (
'use server') that runs on the server. In a Vite single-page app talking to an ASP.NET Core API, the action simply callsfetch.
Server state vs client state
| Client state | Server state | |
|---|---|---|
| Examples | a dialog is open, the selected tab, what's typed in a form | orders, the current user, product prices |
| Owner | your component | the server; you hold a copy |
| Can go stale? | no | yes, the moment it arrives |
| Shared? | rarely | many components want the same data |
| Tools | useState, useReducer, context, a small store | a query cache: TanStack Query, RTK Query, SWR |
Fetching in useEffect and storing the result in useState is fine for a demo and a trap in an app: there's no
cache between pages, no deduplication when three components need the same user, nothing refetches after a
mutation, Strict Mode runs the effect twice in development, and responses can arrive out of order:
const delays: Record<string, number> = { a: 60, ab: 10 };
const search = (q: string) => new Promise<string>((resolve) => setTimeout(() => resolve(`results for "${q}"`), delays[q]));
let shown = '';
for (const q of ['a', 'ab']) {
// what a naive effect does on each keystroke
search(q).then((result) => {
shown = result;
console.log('shown:', shown);
});
}
// the slow response for "a" arrives last and overwrites the right answer
// (not runnable here) the minimum fix in an effect: ignore responses from an outdated run
useEffect(() => {
let ignore = false;
search(query).then((result) => { if (!ignore) setResults(result); });
return () => { ignore = true; };
}, [query]);
A query cache: TanStack Query
TanStack Query keeps server data in a cache keyed by a query key, and every component that uses the same key shares the entry:
import { QueryClient, QueryClientProvider, keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api, type Order } from './api';
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 30_000 } } });
// <QueryClientProvider client={queryClient}><App /></QueryClientProvider>
export const orderKeys = {
all: ['orders'] as const,
list: (status: string, page: number) => ['orders', { status, page }] as const,
detail: (id: string) => ['orders', id] as const,
};
export function OrderList({ status, page }: { status: string; page: number }) {
const { data, isPending, isError, error, isFetching } = useQuery({
queryKey: orderKeys.list(status, page), // every input of queryFn is in the key
queryFn: ({ signal }) => api.orders(status, page, { signal }),
placeholderData: keepPreviousData, // keep showing page 1 while page 2 loads
});
if (isPending) return <Skeleton />;
if (isError) return <ErrorMessage error={error} />;
return <OrderTable orders={data} refreshing={isFetching} />;
}
export function useCreateOrder() {
const client = useQueryClient();
return useMutation({
mutationFn: (order: Omit<Order, 'id'>) => api.createOrder(order),
onSuccess: () => client.invalidateQueries({ queryKey: orderKeys.all }), // every orders query is now stale
});
}
What the cache does for you (exercises 4 and 6 rebuild it):
- Deduplication: components that ask for the same key while a request is running share it.
- Stale-while-revalidate: cached data is shown immediately, and refetched in the background when it's
stale.
staleTime(default0) says how long data counts as fresh;gcTime(default 5 minutes) says how long unused data stays in memory. - Refetch triggers: a component mounting, the window regaining focus, the network reconnecting (for stale data
only), and
invalidateQueriesafter a mutation (for the queries currently on screen). - Two statuses:
statussays whether there's data ('pending' | 'error' | 'success'),fetchStatussays whether a request is running. A background refetch issuccess+fetching: keep the table, show a small spinner. - Retries: failed queries are retried 3 times with exponential backoff by default.
- Keys from general to specific:
['orders'],['orders', { status, page }],['orders', id]. Invalidating['orders']hits all of them, because matching is by prefix. A key factory likeorderKeyskeeps keys consistent across the codebase.
Optimistic updates with rollback
An optimistic update shows the result before the server confirms it. With TanStack Query there are two ways.
Through the UI: render the mutation's variables while it's pending. Nothing to roll back, because the cache is
never touched:
// (not runnable here)
const addTodo = useMutation({ mutationFn: api.addTodo, onSettled: () => client.invalidateQueries({ queryKey: ['todos'] }) });
// in the list: {addTodo.isPending && <li style={{ opacity: 0.5 }}>{addTodo.variables.title}</li>}
Through the cache, with a snapshot to restore:
// (not runnable here)
useMutation({
mutationFn: api.toggleTodo,
onMutate: async (id: string) => {
await client.cancelQueries({ queryKey: ['todos'] }); // a refetch in flight would overwrite the optimistic data
const previous = client.getQueryData<Todo[]>(['todos']);
client.setQueryData<Todo[]>(['todos'], (list = []) => list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
return { previous }; // passed to onError
},
onError: (_error, _id, snapshot) => client.setQueryData(['todos'], snapshot?.previous),
onSettled: () => client.invalidateQueries({ queryKey: ['todos'] }), // resync with the server either way
});
The snapshot approach has one weakness: when two mutations overlap and the first fails, restoring its snapshot
also wipes out the second change. Keeping the confirmed state and the pending actions apart, and replaying the
pending actions on top, avoids it, and that's what useOptimistic does. Exercise 7 builds it. Either way: generate
ids on the client (crypto.randomUUID()), write reducers that are safe to apply twice, and tell the user when a
change was rolled back.
Common mistakes
- Starting a controlled input with
undefined, or giving itvaluewithoutonChange. - Reading
form.get('agree') === 'true'for a checkbox (it's'on'or missing), orgetfor a multi-value field. - Showing every validation error before the user has touched anything, or only English strings that can't be translated or tested.
- No double-submit protection: disable the button with
useFormStatus().pendingorisPending, and guard in code. - Copying query data into
useState"so it can be edited", then wondering why it doesn't update. Edit a copy in a form, and write back through a mutation. - Query keys that miss an input of the query function (page 2 shows page 1's data).
- Throwing from a
useActionStateaction for an expected outcome (it cancels the queue and shows an error boundary). - Optimistic updates without a rollback, or with a rollback that silently drops the user's change.
In a real codebase
Side note
- An API client generated from the backend's OpenAPI document (NSwag, Kiota or openapi-typescript for an ASP.NET
Core API), wrapped in query and mutation hooks per feature (
useOrders,useCreateOrder) with a key factory. - Auth in one place: the fetcher adds the access token (fetched silently from the identity provider by its OIDC
client library) and turns
401,403andValidationProblemDetailsresponses into typed errors. - Forms: React Hook Form with a Zod schema shared by the fields and the submit handler, server errors mapped back onto fields, and the submit button bound to the pending state.
- Lists that people edit: optimistic updates for small, likely-to-succeed changes (toggle, rename, reorder); plain pending states for anything with side effects people care about (payments, emails).
Angular for comparison
Side note
- Reactive forms (
FormGroup,FormControl, validators that return error objects keyed by code) are Angular's controlled forms: the form model is the source of truth, andtouched,dirtyandpendingare built into every control. The TypeScript track's React & Angular patterns topic rebuilds Angular-style validators. - Server state is usually
HttpClientObservables, cached by hand in a service withshareReplayor signals. TanStack Query also has an Angular adapter with the same keys,staleTimeand invalidation. concatMapover a stream of submissions gives the same "one at a time, in order" behaviour asuseActionState's queue (see the RxJS & Observables topic).
The exercises
- Read a form with FormData: strings, missing checkboxes and multi-value fields into a typed object.
- Validation with typed error codes: per-field codes, and a mapped type that forces a message for each.
- A tiny useForm: values, touched, dirty, server errors and a double-submit guard.
- Query keys, hashing and matching: stable hashes and the prefix matching behind invalidation.
- useActionState's action queue: sequential actions, previous state, and cancellation on error.
- A query cache (TanStack Query's core): deduplication, stale-while-revalidate, invalidation and races.
- Optimistic updates with rollback: pending actions replayed on top of confirmed state.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app