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.

13 min read

In short

  • Controlled: React state; uncontrolled: the DOM
  • Start inputs with '', never undefined
  • Validate into typed codes; the server validates too
  • Actions: useActionState and useFormStatus
  • 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>
  );
}
ControlledUncontrolled
Source of truthReact stateThe DOM
Re-rendersOn every keystrokeNone while typing
Good forLive validation, formatting, fields that depend on each other, disabling a button as you typeSimple forms, React 19 form actions, large forms (React Hook Form uses refs)
ResetSet the stateform.reset(), or change the form's key

Things that trip people up:

  • value={undefined} makes an input uncontrolled. If the state starts as undefined and later becomes a string, React warns that "a component is changing an uncontrolled input to be controlled". Start with '', or write value={name ?? ''}.
  • value without onChange is read-only. React keeps putting the old value back.
  • Checkboxes use checked, not value, and read e.target.checked.
  • Everything except a file is a string. <input type="number"> gives "42", and so does FormData. An unchecked checkbox isn't in FormData at all, and a checkbox group sends one entry per checked box:
▶ Try
// 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 onChange fires on every input (like the DOM's input event), 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:

▶ Try
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-invalid on the input and aria-describedby pointing at the message.
  • The server validates too. Client checks are for speed. An ASP.NET Core API answers with a ValidationProblemDetails body, { "title": "...", "status": 400, "errors": { "Email": ["..."] } }, which a small adapter maps to your field errors:
▶ Try
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 (the FormData when 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 from react-dom and must be called in a component inside the <form>. It gives pending, data, method and action for that form.
  • useOptimistic(value, reducer?) returns a value that shows optimistic changes while an action is running and falls back to value when it ends. Call its setter inside an action or startTransition; 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 calls fetch.

Server state vs client state

Client stateServer state
Examplesa dialog is open, the selected tab, what's typed in a formorders, the current user, product prices
Owneryour componentthe server; you hold a copy
Can go stale?noyes, the moment it arrives
Shared?rarelymany components want the same data
ToolsuseState, useReducer, context, a small storea 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:

▶ Try
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 (default 0) 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 invalidateQueries after a mutation (for the queries currently on screen).
  • Two statuses: status says whether there's data ('pending' | 'error' | 'success'), fetchStatus says whether a request is running. A background refetch is success + 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 like orderKeys keeps 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 it value without onChange.
  • Reading form.get('agree') === 'true' for a checkbox (it's 'on' or missing), or get for 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().pending or isPending, 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 useActionState action 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, 403 and ValidationProblemDetails responses 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, and touched, dirty and pending are built into every control. The TypeScript track's React & Angular patterns topic rebuilds Angular-style validators.
  • Server state is usually HttpClient Observables, cached by hand in a service with shareReplay or signals. TanStack Query also has an Angular adapter with the same keys, staleTime and invalidation.
  • concatMap over a stream of submissions gives the same "one at a time, in order" behaviour as useActionState's queue (see the RxJS & Observables topic).

The exercises

  1. Read a form with FormData: strings, missing checkboxes and multi-value fields into a typed object.
  2. Validation with typed error codes: per-field codes, and a mapped type that forces a message for each.
  3. A tiny useForm: values, touched, dirty, server errors and a double-submit guard.
  4. Query keys, hashing and matching: stable hashes and the prefix matching behind invalidation.
  5. useActionState's action queue: sequential actions, previous state, and cancellation on error.
  6. A query cache (TanStack Query's core): deduplication, stale-while-revalidate, invalidation and races.
  7. 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