# React 19 in Practice: Actions, Forms and useOptimistic Patterns

> React 19 form Actions, optimistic UI recipes, use(), ref as prop, metadata, Zod validation, TanStack Query vs RSC, testing, migration and pitfalls.

Source: https://www.derar.dev/blog/react-19-actions-forms-optimistic-ui-patterns-2026 · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

React 19 changed how you write the most common thing in a web app: a user does something, you talk to a server, and the UI reflects the result. Before, every team hand-rolled the same state machine with `isLoading`, `error`, `data`, a `useEffect`, a reset on success, and a race condition or two. React 19 makes that flow a first-class concept called an **Action**, and gives you hooks for the pieces: `useActionState` for the result, `useFormStatus` for pending state in children, `useOptimistic` for instant feedback, and `use` for reading promises and context during render.

An Action is an async function passed to a transition or a form. React tracks its pending state, handles errors through error boundaries, and batches the resulting updates, so you stop writing `isLoading` flags by hand. `<form action={fn}>` accepts a function: React calls it with `FormData`, wraps it in a transition and, on success, resets uncontrolled fields automatically. `useActionState(action, initialState)` returns `[state, formAction, isPending]`. The action receives `(previousState, formData)`, and you use it to return validation errors and results. `useFormStatus()` (from `react-dom`) lets a child component of a form read `pending`, but it only works inside a `form` rendered by a parent component.

`useOptimistic(state, reducer?)` shows a temporary value while an Action is in flight and automatically reverts to the real state when it completes or fails. Call the setter inside an Action or transition. `use(promise)` reads a promise during render and suspends, while `use(Context)` reads context and, unlike `useContext`, can be called conditionally. Promises passed to `use` must be stable (created outside render, or passed from a Server Component), not created fresh each render. `ref` is a regular prop for function components, `forwardRef` becomes unnecessary, and ref callbacks can return a cleanup function. `title`, `meta` and `link` tags render anywhere and are hoisted to the head, and `link rel="stylesheet"` with `precedence` is deduplicated and ordered.

Server Actions (`"use server"`) are public HTTP endpoints. Always validate input with a schema, authenticate and authorize inside the action, and never trust the client. Use Server Components for reading data, Server Actions or client Actions for mutations, and TanStack Query when you need client-side caching, polling, infinite lists or offline behavior. `useTransition` and `useDeferredValue` keep the UI responsive during expensive updates. The React Compiler removes most manual `memo` work, but it does not replace these.

Test behavior with Testing Library and `userEvent`, wrap async updates with `act` from `react`, and assert on roles and visible text rather than implementation details. Migrating from 18: update to 18.3 first (warnings), run the official codemods, replace removed APIs (`ReactDOM.render`, `propTypes`, string refs, `defaultProps` on function components), then upgrade types.

React 19 shipped in December 2024; 19.1 followed in 2025 and 19.2 in October 2025 (adding `Activity`, `useEffectEvent` and more). The 19.2.x line is stable as of November 2026. Check the [React blog](https://react.dev/blog) for the current patch and any 19.3 changes before upgrading. The APIs below are the ones documented on [react.dev](https://react.dev).

## Decision table: which tool for which problem

| Problem | Reach for | Not this | Why |
| --- | --- | --- | --- |
| Submit a form and show server errors | `<form action>` + `useActionState` | `onSubmit` + `useState` flags | Pending, result and reset are built in |
| Disable a submit button while pending | `useFormStatus` in a child, or `isPending` from `useActionState` | Manual `loading` state | One source of truth |
| Instant feedback for a like, toggle or add | `useOptimistic` | Mutating local state and rolling back by hand | Auto-revert on failure |
| Read async data in a client component | `use(promise)` with `Suspense`, with a stable promise | `useEffect` + `useState` fetch | Fewer renders, no waterfall of flags |
| Read context conditionally | `use(Context)` | `useContext` behind a hoisted wrapper | Allowed after early returns |
| Mutate data with server logic | Server Action | Hand-written API route plus fetch | Colocated, typed, progressive enhancement |
| Rich client cache, polling, infinite scroll | TanStack Query | Server Actions as a cache | Cache keys, stale-while-revalidate |
| Keep typing responsive while filtering a big list | `useDeferredValue` or `useTransition` | Debounce for rendering cost | Interruptible rendering |
| Avoid re-renders | React Compiler first | `memo` everywhere | Compiler memoizes automatically |
| Share a ref with a parent | `ref` prop | `forwardRef` | Simpler, `forwardRef` is on a deprecation path |

## The mental model: Actions and transitions

### What an Action is

An **Action** is a function you pass to React that performs an update that may be async: submit a form, call an API, then update UI. By convention, functions that run inside a transition are called Actions. React provides three things for them:

1. **Pending state.** While the Action runs, `isPending` is true (from `useTransition`, `useActionState`, or `useFormStatus`).
2. **Optimistic updates.** `useOptimistic` can show the expected result immediately.
3. **Error handling.** If the Action throws, React rethrows to the nearest error boundary and reverts optimistic state. Updates are batched, so the UI does not flicker through partial states.

### Transitions can be async now

In React 18, `startTransition` accepted only synchronous callbacks. In React 19 it accepts async functions:

```tsx
import { useState, useTransition } from "react";

export function RenameButton({ id, name }: { id: string; name: string }) {
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function rename(next: string) {
    startTransition(async () => {
      setError(null);
      const res = await fetch(`/api/items/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: next }),
      });
      if (!res.ok) {
        setError("Could not rename the item.");
        return;
      }
      // updates after an await are not automatically part of the transition:
      // wrap them again if they must be low priority
      startTransition(() => {
        /* e.g. setSomeLowPriorityState(...) */
      });
    });
  }

  return (
    <>
      <button disabled={isPending} onClick={() => rename(name + " copy")}>
        {isPending ? "Renaming..." : "Duplicate name"}
      </button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}
```

One caveat worth memorizing: state updates **after** an `await` inside a transition are no longer marked as part of that transition unless you wrap them in another `startTransition`. The React docs call this out explicitly; it is a known limitation of the current implementation. Keep post-await updates simple, or wrap them.

### Errors from Actions

If an Action throws and nothing catches it, React surfaces the error to the closest error boundary. For user-correctable problems (validation, "email already taken"), do not throw; return them as state. Throw only for exceptional failures.

| Failure type | How to handle |
| --- | --- |
| Validation error, business rule | Return as state from the action |
| Network failure, 5xx | Throw (or return a retryable state) and let the error boundary or a toast handle it |
| Authorization failure | Redirect or throw to a boundary that shows a sign-in prompt |
| Unexpected bug | Throw; report via `onCaughtError` / `onUncaughtError` on the root |

React 19 added root options to report errors in one place:

```tsx
import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root")!, {
  onCaughtError(error, info) {
    reportError("caught", error, info.componentStack);
  },
  onUncaughtError(error, info) {
    reportError("uncaught", error, info.componentStack);
  },
  onRecoverableError(error, info) {
    reportError("recoverable", error, info.componentStack);
  },
});
```

## Form actions

### The basics

Pass a function to the `action` prop of a `form`. React calls it with a `FormData` object when the form submits, and prevents the default navigation.

```tsx
async function subscribe(formData: FormData) {
  const email = String(formData.get("email") ?? "");
  await fetch("/api/subscribe", { method: "POST", body: JSON.stringify({ email }) });
}

export function Newsletter() {
  return (
    <form action={subscribe}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" autoComplete="email" required />
      <button type="submit">Subscribe</button>
    </form>
  );
}
```

Points that matter:

- The function receives `FormData`. Inputs are read by their `name` attribute, so every input needs a `name`.
- The form runs inside a transition, so React knows when it is pending.
- **After a successful action, React resets uncontrolled form fields** (it calls the form's reset behavior). That is usually what you want after a successful submit, and a surprise when you return validation errors and the user's typed values disappear. The `useActionState` section covers how to preserve them.
- `formAction` on a `button` or `input type="submit"` overrides the form's action for that button, which is how you build forms with several actions ("Save draft", "Publish").

```tsx
<form action={save}>
  <textarea name="body" />
  <button type="submit">Save</button>
  <button type="submit" formAction={publish}>Publish</button>
</form>
```

### Progressive enhancement

When the action is a Server Action (see the Server Actions section) and the form is rendered by a framework that supports it, the form works **before JavaScript loads**: the browser submits it as a normal POST and the server runs the action. That is a real accessibility and resilience benefit. Client-only function actions need JavaScript to run; if you need no-JS support, use Server Actions (or a framework equivalent).

### Controlled inputs still work

You can use controlled inputs with form actions, but you often do not need them. Reading `FormData` is simpler. Use controlled inputs for live formatting, dependent fields or live validation. If you keep controlled state, remember that the automatic form reset only affects uncontrolled fields, so reset your state explicitly after success.

### `requestSubmit` and programmatic submission

To submit a form from code (for example, on a select change), call `form.requestSubmit()`, not `form.submit()`. `requestSubmit` fires the submit event, runs validation and triggers React's action handling. `submit()` bypasses them.

## `useActionState`

### Signature and behavior

```ts
const [state, formAction, isPending] = useActionState(action, initialState, permalink?);
```

- `action` has the signature `(previousState, formData) => newState | Promise<newState>`.
- `state` starts as `initialState` and becomes the last value the action returned.
- `formAction` is what you pass to `form action`.
- `isPending` is true while the action runs.
- `permalink` is an optional URL used by Server Actions to support progressive enhancement across navigations (verify details in the docs).

React runs actions for a given `useActionState` **sequentially**, in order of submission, with each receiving the previous result.

### A complete example: signup with validation

```tsx
"use client";
import { useActionState } from "react";

type SignupState = {
  ok: boolean;
  message?: string;
  fieldErrors?: { email?: string[]; password?: string[] };
  values?: { email: string };
};

async function signupAction(_prev: SignupState, formData: FormData): Promise<SignupState> {
  const email = String(formData.get("email") ?? "").trim();
  const password = String(formData.get("password") ?? "");

  const fieldErrors: NonNullable<SignupState["fieldErrors"]> = {};
  if (!/^\S+@\S+\.\S+$/.test(email)) fieldErrors.email = ["Enter a valid email address."];
  if (password.length < 12) fieldErrors.password = ["Use at least 12 characters."];
  if (Object.keys(fieldErrors).length > 0) {
    // return the values so the form can refill them: React resets uncontrolled inputs on success only
    return { ok: false, fieldErrors, values: { email } };
  }

  const res = await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  if (res.status === 409) return { ok: false, fieldErrors: { email: ["That email is already registered."] }, values: { email } };
  if (!res.ok) throw new Error("Signup failed");
  return { ok: true, message: "Account created. Check your inbox." };
}

export function SignupForm() {
  const [state, formAction, isPending] = useActionState<SignupState, FormData>(signupAction, { ok: false });

  return (
    <form action={formAction} noValidate>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        autoComplete="email"
        defaultValue={state.values?.email}
        aria-invalid={state.fieldErrors?.email ? true : undefined}
        aria-describedby={state.fieldErrors?.email ? "email-error" : undefined}
      />
      {state.fieldErrors?.email && <p id="email-error">{state.fieldErrors.email[0]}</p>}

      <label htmlFor="password">Password</label>
      <input
        id="password"
        name="password"
        type="password"
        autoComplete="new-password"
        aria-invalid={state.fieldErrors?.password ? true : undefined}
        aria-describedby={state.fieldErrors?.password ? "password-error" : undefined}
      />
      {state.fieldErrors?.password && <p id="password-error">{state.fieldErrors.password[0]}</p>}

      <button type="submit" disabled={isPending}>{isPending ? "Creating..." : "Create account"}</button>
      <p role="status">{state.ok ? state.message : null}</p>
    </form>
  );
}
```

The accessibility attributes in this example follow the patterns from [Web Accessibility for Developers](https://www.derar.dev/blog/web-accessibility-wcag-developer-guide-2026): errors are text, associated with the field, and announced through a status region.

### Preserving typed values on error

The behavior to know: React resets the form after the action **completes**. In practice, when an action returns an error state, the form's uncontrolled inputs are reset too, which means a user who typed a long message loses it. Two reliable solutions:

1. Return the submitted values in state and use them as `defaultValue` (as above). Because the input is re-rendered with a new `defaultValue` after reset, the user sees their value.
2. Use controlled inputs for fields where loss is costly (long text), updating state on change, and reset them only on success.

Whether the automatic reset happens on error is a detail that has surprised many developers and has been discussed in the React repository; verify the behavior on the version you use, and write a test (see the testing section) that locks it in.

### Progressive enhancement with Server Actions

With a Server Action, the same hook works without JavaScript on the first load:

```tsx
// app/signup/actions.ts
"use server";
import { z } from "zod";

const schema = z.object({
  email: z.email("Enter a valid email address."),
  password: z.string().min(12, "Use at least 12 characters."),
});

export type SignupState = {
  ok: boolean;
  fieldErrors?: Record<string, string[] | undefined>;
  values?: { email: string };
};

export async function signup(_prev: SignupState, formData: FormData): Promise<SignupState> {
  const raw = { email: String(formData.get("email") ?? ""), password: String(formData.get("password") ?? "") };
  const parsed = schema.safeParse(raw);
  if (!parsed.success) {
    return { ok: false, fieldErrors: z.flattenError(parsed.error).fieldErrors, values: { email: raw.email } };
  }
  // create the user, hash the password, send email...
  return { ok: true };
}
```

```tsx
// app/signup/page.tsx (client component for the form)
"use client";
import { useActionState } from "react";
import { signup, type SignupState } from "./actions";

export function SignupForm() {
  const [state, formAction, isPending] = useActionState<SignupState, FormData>(signup, { ok: false });
  /* same JSX as before */
  return <form action={formAction}>{/* ... */}<button disabled={isPending}>Sign up</button></form>;
}
```

The Zod calls above use the Zod 4 API (`z.email()` as a top-level string format and `z.flattenError`). In Zod 3 they are `z.string().email()` and `error.flatten()`. Verify against the Zod version you install.

## `useFormStatus`

`useFormStatus` returns `{ pending, data, method, action }` for the **parent form**. It is exported from `react-dom` and must be called from a component rendered **inside** the form, not in the component that renders the form.

```tsx
"use client";
import { useFormStatus } from "react-dom";

export function SubmitButton({ children, pendingLabel }: { children: React.ReactNode; pendingLabel: string }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} aria-disabled={pending}>
      {pending ? pendingLabel : children}
    </button>
  );
}
```

```tsx
<form action={createPost}>
  <input name="title" />
  <SubmitButton pendingLabel="Publishing...">Publish</SubmitButton>
</form>
```

This is ideal for design-system components: a `SubmitButton`, a spinner, or a fieldset that disables itself during submission, with no props threading. A frequent bug is calling `useFormStatus` in the same component that renders the `form`: it then reports `pending: false` forever because there is no parent form. Move the hook into a child.

Also read `data` for the pending submission: it gives you the `FormData` currently being submitted, which is handy to render an optimistic row without lifting state.

## `useOptimistic`

### Signature and rules

```ts
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn?);
```

- `state` is the real, committed value (from props, server data or `useState`).
- `optimisticState` equals `state` normally, and the temporary value while an Action is in flight.
- `addOptimistic(value)` applies `updateFn(currentState, value)` (or replaces the state when no `updateFn` is given) for the duration of the Action.
- It must be called **inside an Action or transition** (for example, inside `<form action>` or `startTransition`). Calling it outside warns in development.
- When the Action finishes, React discards the optimistic value and renders `state`. If the Action succeeded and you updated the real state, the UI shows the real result. If it failed, the UI reverts. You do not write rollback code.

### Recipe: like button

```tsx
"use client";
import { useOptimistic, useState, useTransition } from "react";

type LikeState = { liked: boolean; count: number };

export function LikeButton({ postId, initial, toggleLike }: {
  postId: string;
  initial: LikeState;
  toggleLike: (postId: string, nextLiked: boolean) => Promise<LikeState>;
}) {
  const [committed, setCommitted] = useState(initial);
  const [optimistic, setOptimistic] = useOptimistic(committed, (current, nextLiked: boolean) => ({
    liked: nextLiked,
    count: current.count + (nextLiked ? 1 : -1),
  }));
  const [, startTransition] = useTransition();

  function onClick() {
    const nextLiked = !optimistic.liked;
    startTransition(async () => {
      setOptimistic(nextLiked);
      const server = await toggleLike(postId, nextLiked);
      setCommitted(server); // the real value replaces the optimistic one
    });
  }

  return (
    <button type="button" aria-pressed={optimistic.liked} onClick={onClick}>
      {optimistic.liked ? "Liked" : "Like"} ({optimistic.count})
    </button>
  );
}
```

Note `aria-pressed` for toggle semantics.

### Recipe: todo list with form action

```tsx
"use client";
import { useOptimistic } from "react";

type Todo = { id: string; title: string; done: boolean; pending?: boolean };

export function Todos({ todos, addTodo }: { todos: Todo[]; addTodo: (title: string) => Promise<void> }) {
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(
    todos,
    (current: Todo[], title: string) => [...current, { id: `tmp-${crypto.randomUUID()}`, title, done: false, pending: true }],
  );

  async function action(formData: FormData) {
    const title = String(formData.get("title") ?? "").trim();
    if (!title) return;
    addOptimisticTodo(title);
    await addTodo(title); // when this resolves, parent refreshes `todos` (revalidate or setState)
  }

  return (
    <>
      <form action={action}>
        <label htmlFor="title">New task</label>
        <input id="title" name="title" required />
        <button type="submit">Add</button>
      </form>
      <ul>
        {optimisticTodos.map((todo) => (
          <li key={todo.id} aria-busy={todo.pending ? true : undefined} style={{ opacity: todo.pending ? 0.6 : 1 }}>
            {todo.title}
          </li>
        ))}
      </ul>
    </>
  );
}
```

The parent must update `todos` when the action completes (with a Server Action that calls `revalidatePath`, a router refresh, or a state setter). The temporary item uses a temporary id; when real data arrives, React shows the real list and the temporary item disappears, so make sure the real list contains the new item, or the item will vanish.

### Recipe: shopping cart quantity

```tsx
"use client";
import { useOptimistic, startTransition } from "react";

type CartLine = { sku: string; name: string; qty: number; unitPrice: number };

export function Cart({ lines, updateQty }: { lines: CartLine[]; updateQty: (sku: string, qty: number) => Promise<void> }) {
  const [optimisticLines, setOptimisticQty] = useOptimistic(
    lines,
    (current: CartLine[], change: { sku: string; qty: number }) =>
      change.qty <= 0
        ? current.filter((l) => l.sku !== change.sku)
        : current.map((l) => (l.sku === change.sku ? { ...l, qty: change.qty } : l)),
  );

  const total = optimisticLines.reduce((sum, l) => sum + l.qty * l.unitPrice, 0);

  function change(sku: string, qty: number) {
    startTransition(async () => {
      setOptimisticQty({ sku, qty });
      await updateQty(sku, qty);
    });
  }

  return (
    <section aria-label="Cart">
      <ul>
        {optimisticLines.map((l) => (
          <li key={l.sku}>
            {l.name}
            <button type="button" aria-label={`Decrease quantity of ${l.name}`} onClick={() => change(l.sku, l.qty - 1)}>-</button>
            <output aria-live="polite">{l.qty}</output>
            <button type="button" aria-label={`Increase quantity of ${l.name}`} onClick={() => change(l.sku, l.qty + 1)}>+</button>
          </li>
        ))}
      </ul>
      <p>Total: {(total / 100).toFixed(2)}</p>
    </section>
  );
}
```

Money is stored in minor units (cents) to avoid floating point issues. A derived value (`total`) is computed from the optimistic state, so it updates instantly.

### Optimistic UI: rules of thumb

| Do | Do not |
| --- | --- |
| Use for actions that succeed almost always (likes, toggles, adds, reorder) | Use for payments, destructive deletes without undo, or anything with a high failure rate |
| Show a subtle pending style on optimistic rows | Pretend the data is saved with no indication in slow networks |
| Keep the optimistic reducer pure and small | Put network code inside the reducer |
| Reconcile with the server response | Assume the server accepted the exact optimistic value |
| Surface failures (toast, inline message) after the revert | Silently revert so the user wonders what happened |
| Remember concurrent optimistic updates stack in order | Rely on optimistic state surviving navigation |

## Server Actions versus client Actions

### Two meanings of "Action"

| | Client Action | Server Action |
| --- | --- | --- |
| Where it runs | Browser | Server (called from client over an automatic network request) |
| Marked with | Nothing; any function passed to a form or transition | `"use server"` at top of function or file |
| Typical use | Calls your REST or GraphQL API, local state | Direct DB access, secrets, server-only logic |
| Works without JS | No | Yes, when used as a form action with a supporting framework |
| Security surface | Your API's | The action is a **public endpoint** |
| Return value | Anything | Serializable values only |

### Server Actions are public endpoints

A Server Action compiles into an HTTP endpoint that anyone can call with crafted input, regardless of whether your UI exposes a button. Treat every one like an API route:

```ts
// app/projects/actions.ts
"use server";
import { z } from "zod";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";

const renameSchema = z.object({
  id: z.uuid(),
  name: z.string().trim().min(1).max(80),
});

export async function renameProject(_prev: unknown, formData: FormData) {
  const session = await auth();
  if (!session) return { ok: false as const, message: "Please sign in." };

  const parsed = renameSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) {
    return { ok: false as const, fieldErrors: z.flattenError(parsed.error).fieldErrors };
  }

  // authorization: the user must own this project
  const project = await db.project.findFirst({ where: { id: parsed.data.id, ownerId: session.user.id } });
  if (!project) return { ok: false as const, message: "Project not found." };

  await db.project.update({ where: { id: project.id }, data: { name: parsed.data.name } });
  revalidatePath("/projects");
  return { ok: true as const };
}
```

Checklist for every Server Action:

1. Authenticate (who is calling?).
2. Authorize (may they act on **this** resource id?).
3. Validate every input with a schema; `FormData` values are untrusted strings.
4. Rate limit sensitive actions (login, password reset, expensive work).
5. Return serializable results and avoid leaking internals in error messages.
6. Do not pass secrets or closures capturing sensitive values from Server Components into actions defined inline; closed-over values are encrypted by Next.js but still are part of the request (verify the framework's security notes).

Next.js specifics (cache invalidation, `revalidatePath`, `revalidateTag`, how data caching interacts with actions) are covered in [Next.js Server Components, Caching and Data Patterns](https://www.derar.dev/blog/nextjs-server-components-caching-data-patterns-2026); this article does not repeat them.

### Server Actions execute one at a time per client

Calls to Server Actions from the same client are queued and run sequentially. That makes them a poor fit for parallel data fetching: use Server Components or a client data library to read, and actions for writes. For rapid-fire writes (typing a draft), debounce or batch on the client.

### Client Actions with your existing API

If you already have a REST API and are not using a framework with Server Actions, client Actions give you most of the benefits (pending, errors, optimistic UI, form reset). Only progressive enhancement is lost.

```tsx
async function updateProfile(_prev: ProfileState, formData: FormData): Promise<ProfileState> {
  const res = await fetch("/api/profile", { method: "PUT", body: formData });
  if (res.status === 422) return { ok: false, fieldErrors: (await res.json()).errors };
  if (!res.ok) throw new Error(`Profile update failed with ${res.status}`);
  return { ok: true };
}
```

## The `use` API and Suspense

### `use` with promises

`use(promise)` reads the resolved value of a promise during render. While the promise is pending, the component suspends and the nearest `Suspense` boundary shows its fallback. If the promise rejects, the nearest error boundary renders.

```tsx
// page.tsx (Server Component): create the promise on the server and pass it down
import { Suspense } from "react";
import { Comments } from "./comments";

export default function Page({ params }: { params: Promise<{ id: string }> }) {
  const commentsPromise = params.then(({ id }) => fetchComments(id));
  return (
    <article>
      <h1>Post</h1>
      <Suspense fallback={<p>Loading comments...</p>}>
        <Comments commentsPromise={commentsPromise} />
      </Suspense>
    </article>
  );
}
```

```tsx
// comments.tsx
"use client";
import { use } from "react";

type Comment = { id: string; author: string; body: string };

export function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
  const comments = use(commentsPromise);
  return (
    <ul>
      {comments.map((c) => (
        <li key={c.id}><strong>{c.author}</strong>: {c.body}</li>
      ))}
    </ul>
  );
}
```

Passing a promise from a Server Component to a Client Component and reading it with `use` lets the server start the fetch immediately and stream the result, without blocking the page shell. This is the recommended pattern.

### The stable promise rule

Creating a promise **inside** a client component's render and passing it to `use` causes an infinite loop of suspensions, because every render makes a new promise. React warns about this ("A component was suspended by an uncached promise"). Acceptable sources for the promise:

- Created in a Server Component and passed as a prop (React serializes it).
- Created in a cache or a module-level `Map` keyed by input.
- Created by a Suspense-compatible library (TanStack Query's `useSuspenseQuery`, Relay, framework loaders).
- Memoized with `useMemo` only as a last resort; React does not guarantee that memoization persists across suspensions, so the docs advise against relying on it.

```tsx
// A small client-side cache to give use() a stable promise
const cache = new Map<string, Promise<unknown>>();

export function cachedFetch<T>(url: string): Promise<T> {
  if (!cache.has(url)) {
    cache.set(url, fetch(url).then((r) => {
      if (!r.ok) throw new Error(`Request failed: ${r.status}`);
      return r.json();
    }));
  }
  return cache.get(url) as Promise<T>;
}
```

A hand-rolled cache like this has no invalidation, no eviction and no retries. It is fine for a demo; in production use a library or a framework loader.

### `use` with Context

```tsx
import { use, createContext } from "react";

const ThemeContext = createContext<"light" | "dark">("light");

function Heading({ children, important }: { children: React.ReactNode; important: boolean }) {
  if (!important) return <h2>{children}</h2>;
  const theme = use(ThemeContext); // allowed after an early return, unlike useContext
  return <h2 className={theme === "dark" ? "text-white" : "text-black"}>{children}</h2>;
}
```

React 19 also lets you render the context itself as a provider: `<ThemeContext value="dark">` instead of `<ThemeContext.Provider value="dark">`. The old form still works; a codemod will migrate it eventually.

### Suspense design

| Guideline | Why |
| --- | --- |
| Place boundaries around independent regions (comments, recommendations) | One slow region does not block the others |
| Provide a skeleton that matches the final layout | Avoids layout shift |
| Do not wrap the entire app in one boundary | A single fallback replaces everything on every suspension |
| Pair with an error boundary per region | One failure does not blank the page |
| Use `startTransition` for navigation-style updates | Keeps old UI visible instead of flashing fallbacks |

In React 19, when a component suspends, sibling components in the same boundary no longer render until the suspended one is ready (a change from 18 that avoids wasted work and layout oddities). If you rely on siblings starting their own fetches concurrently, start those requests **above** the boundary and pass promises down.

## Quality-of-life features: refs, cleanup, metadata, stylesheets

### `ref` as a prop

Function components receive `ref` like any prop. No `forwardRef` needed:

```tsx
function Input({ ref, ...props }: React.ComponentProps<"input">) {
  return <input ref={ref} {...props} />;
}

function Form() {
  const inputRef = useRef<HTMLInputElement>(null);
  return (
    <>
      <Input ref={inputRef} name="q" />
      <button type="button" onClick={() => inputRef.current?.focus()}>Focus</button>
    </>
  );
}
```

`React.ComponentProps<"input">` already includes `ref` in React 19 types. `forwardRef` still works but is expected to be deprecated in a future release; a codemod exists to migrate. Class components do not receive `ref` as a prop (it is still the instance ref).

### Ref callback cleanup

A ref callback can now return a cleanup function, called when the element is removed (or when the ref changes). This replaces the old pattern of receiving `null` on unmount:

```tsx
<div
  ref={(node) => {
    if (!node) return;
    const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
    observer.observe(node);
    return () => observer.disconnect();
  }}
/>
```

Because a returned value now means "cleanup", arrow functions that implicitly return something (for example `ref={el => (instance = el)}`) now fail type checking; use braces so nothing is returned. The React 19 TypeScript changes and codemods handle most cases.

### Document metadata

Render `title`, `meta` and `link` anywhere; React hoists them to `head`:

```tsx
function BlogPost({ post }: { post: { title: string; summary: string; slug: string } }) {
  return (
    <article>
      <title>{post.title}</title>
      <meta name="description" content={post.summary} />
      <link rel="canonical" href={`https://example.com/blog/${post.slug}`} />
      <h1>{post.title}</h1>
    </article>
  );
}
```

Frameworks (Next.js `metadata` API, React Router) have their own conventions that integrate with streaming and deduplication; prefer them in a framework app and use native tags for plain React apps. For accessibility, a unique `title` per route matters (WCAG 2.4.2).

### Stylesheets and resource hints

```tsx
function Widget() {
  return (
    <>
      <link rel="stylesheet" href="/widget.css" precedence="default" />
      <div className="widget">...</div>
    </>
  );
}
```

With `precedence`, React inserts the stylesheet in the correct order, deduplicates repeated renders and, during streaming, waits for it to load before revealing content that depends on it, which avoids flashes of unstyled content. Async scripts rendered in any component are also deduplicated. For hints, `react-dom` exports `preconnect`, `prefetchDNS`, `preload`, `preloadModule`, `preinit` and `preinitModule`:

```tsx
import { preconnect, preload } from "react-dom";

function Page() {
  preconnect("https://images.example.com");
  preload("/fonts/inter.woff2", { as: "font", type: "font/woff2", crossOrigin: "anonymous" });
  return <main>...</main>;
}
```

### Other 19.x changes worth knowing

| Change | Notes |
| --- | --- |
| `useDeferredValue(value, initialValue)` | Optional initial value rendered first, then the deferred value in the background |
| Better hydration error messages | A single diff-style message instead of several vague warnings |
| Custom Elements support | Properties and attributes pass through correctly |
| `useEffectEvent` (19.2) | Extract non-reactive logic out of effects; do not add it to dependency arrays |
| `Activity` (19.2) | Hide and show UI while preserving state; verify current API and mode names in the docs |
| `cacheSignal` (19.2, Server Components) | Abort work when the cache lifetime ends |
| React Performance Tracks (19.2) | Custom tracks in the Chrome performance profiler |
| `eslint-plugin-react-hooks` recent versions | Include compiler-powered rules; verify version and config name |

## Validation and error-handling patterns

### One schema, shared by client and server

Define the schema once and use it in the browser for fast feedback and on the server as the source of truth:

```ts
// lib/schemas.ts
import { z } from "zod";

export const contactSchema = z.object({
  name: z.string().trim().min(2, "Enter your name."),
  email: z.email("Enter a valid email address."),
  message: z.string().trim().min(20, "Tell us a bit more (at least 20 characters).").max(2000),
});

export type ContactInput = z.infer<typeof contactSchema>;
```

### A reusable action-result type

```ts
// lib/action-result.ts
export type FieldErrors = Record<string, string[] | undefined>;

export type ActionResult<T = undefined> =
  | { status: "idle" }
  | { status: "success"; data: T; message?: string }
  | { status: "error"; message?: string; fieldErrors?: FieldErrors; values?: Record<string, string> };

export const idle: ActionResult = { status: "idle" };
```

```ts
// lib/with-validation.ts
import { z } from "zod";
import type { ActionResult } from "./action-result";

export function validateForm<S extends z.ZodType>(schema: S, formData: FormData) {
  const values = Object.fromEntries(
    [...formData.entries()].filter(([, v]) => typeof v === "string"),
  ) as Record<string, string>;
  const parsed = schema.safeParse(values);
  if (parsed.success) return { ok: true as const, data: parsed.data as z.infer<S>, values };
  const error: ActionResult = {
    status: "error",
    fieldErrors: z.flattenError(parsed.error).fieldErrors as Record<string, string[]>,
    values,
  };
  return { ok: false as const, error, values };
}
```

```ts
// app/contact/actions.ts
"use server";
import { contactSchema } from "@/lib/schemas";
import { validateForm } from "@/lib/with-validation";
import type { ActionResult } from "@/lib/action-result";

export async function sendContact(_prev: ActionResult, formData: FormData): Promise<ActionResult> {
  const result = validateForm(contactSchema, formData);
  if (!result.ok) return result.error;

  try {
    await deliver(result.data); // send email or write to DB
    return { status: "success", data: undefined, message: "Thanks, we will reply within two business days." };
  } catch {
    return { status: "error", message: "We could not send your message. Please try again.", values: result.values };
  }
}
```

### A field component that reads the result

```tsx
"use client";
import { useId } from "react";

export function Field({ label, name, error, defaultValue, type = "text", ...rest }: {
  label: string;
  name: string;
  error?: string;
  defaultValue?: string;
  type?: string;
} & Omit<React.ComponentProps<"input">, "name" | "type" | "defaultValue">) {
  const id = useId();
  const errorId = `${id}-error`;
  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input
        id={id}
        name={name}
        type={type}
        defaultValue={defaultValue}
        aria-invalid={error ? true : undefined}
        aria-describedby={error ? errorId : undefined}
        {...rest}
      />
      {error && <p id={errorId}>{error}</p>}
    </div>
  );
}
```

### Error boundaries and recovery

Use error boundaries for exceptional failures, and give users a retry. A minimal boundary using `react-error-boundary`:

```tsx
import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary
  fallbackRender={({ error, resetErrorBoundary }) => (
    <div role="alert">
      <p>Something went wrong.</p>
      <button type="button" onClick={resetErrorBoundary}>Try again</button>
    </div>
  )}
  onError={(error, info) => reportError(error, info.componentStack)}
>
  <Comments commentsPromise={commentsPromise} />
</ErrorBoundary>
```

In Next.js App Router, an `error.tsx` file serves as the boundary for a route segment.

### Idempotency and double submits

Users double-click, networks retry. Make mutations safe: disable the button while pending (the Action's `isPending`), send an idempotency key for payments and creation endpoints, and make the server reject duplicates.

```tsx
<form action={formAction}>
  <input type="hidden" name="idempotencyKey" value={useMemo(() => crypto.randomUUID(), [])} />
</form>
```

Generate the key once per intended submission (not per render), and rotate it after success. The `useMemo` call above is illustrative: hooks must be called at the top level of a component, so in real code call `useMemo` or `useState(() => crypto.randomUUID())` before the return statement and use the variable.

## Data fetching: Server Components, `use`, and TanStack Query

### Division of labor

| Concern | Best tool |
| --- | --- |
| Initial page data, SEO content | Server Components (fetch on the server, stream) |
| Mutations with server logic | Server Actions (or API route plus client Action) |
| Client-side cache, background refetch, polling, window focus refetch | TanStack Query |
| Infinite scroll, pagination with cached pages | TanStack Query (`useInfiniteQuery`) |
| Offline and retry behavior | TanStack Query (with persistence) |
| One-off async value passed to a client component | `use(promise)` from a Server Component |
| Real-time streams | WebSocket or SSE with a store; not Actions |

They are complementary. The common 2026 architecture is: Server Components render the first view and prefetch data, hydrate it into TanStack Query's cache for client interactions, and mutations are Server Actions that invalidate both the framework cache and the query cache.

### Hydrating prefetched data into TanStack Query

```tsx
// app/projects/page.tsx (Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";
import { ProjectList } from "./project-list";
import { getProjects } from "@/lib/projects";

export default async function Page() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery({ queryKey: ["projects"], queryFn: getProjects });

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <ProjectList />
    </HydrationBoundary>
  );
}
```

```tsx
// app/projects/project-list.tsx
"use client";
import { useSuspenseQuery } from "@tanstack/react-query";

export function ProjectList() {
  const { data } = useSuspenseQuery({ queryKey: ["projects"], queryFn: () => fetch("/api/projects").then((r) => r.json()) });
  return <ul>{data.map((p: { id: string; name: string }) => <li key={p.id}>{p.name}</li>)}</ul>;
}
```

### Optimistic updates: TanStack Query versus `useOptimistic`

| | `useOptimistic` | TanStack Query optimistic updates |
| --- | --- | --- |
| Scope | One component tree, tied to an Action | Shared cache; all consumers update |
| Revert | Automatic when the Action ends | Manual rollback in `onError` with a snapshot, or the variables-based UI approach |
| Best for | Local feedback tied to a form or button | Data shown in many places (list, detail, header counter) |
| Complexity | Low | Medium |

Use `useOptimistic` when the optimistic state matters in one place. Use query-cache updates when many components display the same entity. TanStack Query v5 also supports rendering optimistic UI directly from `useMutation` variables, which is the simplest option when a single list shows the pending item (verify the pattern on the TanStack docs).

### Avoiding waterfalls

```tsx
// Slow: sequential awaits
const user = await getUser(id);
const posts = await getPosts(user.id);

// Better when independent: start both, then await
const [user, stats] = await Promise.all([getUser(id), getStats(id)]);

// Streaming: pass unresolved promises to client components and use() them behind Suspense
```

## Concurrency: `useTransition` and `useDeferredValue`

Concurrent rendering lets React interrupt low-priority rendering for urgent updates. Two hooks expose it.

### `useTransition` for updates you trigger

```tsx
"use client";
import { useState, useTransition } from "react";

export function TabbedReport({ reports }: { reports: Record<string, React.ReactNode> }) {
  const [tab, setTab] = useState("summary");
  const [isPending, startTransition] = useTransition();

  return (
    <div>
      <div role="tablist" aria-label="Report sections">
        {Object.keys(reports).map((key) => (
          <button
            key={key}
            role="tab"
            aria-selected={tab === key}
            onClick={() => startTransition(() => setTab(key))}
          >
            {key}
          </button>
        ))}
      </div>
      <div role="tabpanel" aria-busy={isPending} style={{ opacity: isPending ? 0.7 : 1 }}>
        {reports[tab]}
      </div>
    </div>
  );
}
```

The old content stays visible (dimmed) while the heavy new tab renders, rather than flashing a Suspense fallback. For a complete tabs implementation with keyboard behavior see the accessibility article.

### `useDeferredValue` for values you receive

```tsx
"use client";
import { useDeferredValue, useMemo, useState } from "react";

export function Search({ items }: { items: string[] }) {
  const [query, setQuery] = useState("");
  const deferredQuery = useDeferredValue(query);
  const stale = query !== deferredQuery;

  const results = useMemo(
    () => items.filter((item) => item.toLowerCase().includes(deferredQuery.toLowerCase())),
    [items, deferredQuery],
  );

  return (
    <>
      <label htmlFor="q">Search</label>
      <input id="q" value={query} onChange={(e) => setQuery(e.target.value)} />
      <ul style={{ opacity: stale ? 0.6 : 1 }}>
        {results.map((r) => <li key={r}>{r}</li>)}
      </ul>
    </>
  );
}
```

The input stays responsive because typing updates `query` immediately, while the expensive list rerenders with the deferred value and can be interrupted.

### Which one

| Situation | Use |
| --- | --- |
| You own the `setState` call | `useTransition` |
| The value comes from props or a parent you cannot change | `useDeferredValue` |
| Network latency is the problem | Suspense, Actions, caching; transitions do not speed up the network |
| The cost is rendering 10,000 rows | Virtualize the list; transitions only keep the UI responsive |

Neither is a debounce: they do not reduce the number of renders attempted or requests made. Debounce network requests separately.

## The React Compiler and these patterns

The React Compiler (stable 1.0 since late 2025) automatically memoizes components and hooks at build time, which removes most manual `useMemo`, `useCallback` and `memo`. It composes cleanly with Actions, `useOptimistic` and `use`: all follow the rules of React, and the compiler relies on those rules. Practical guidance:

- Enable it incrementally (per directory or with the opt-in annotation mode) and measure.
- Keep render functions pure. Mutating props, reading refs during render or creating side effects in render can make the compiler skip a component or produce wrong output.
- Keep using `useTransition` and `useDeferredValue`: they are about scheduling, not memoization.
- Install the lint rules from `eslint-plugin-react-hooks` to surface compiler bailouts (verify the current preset names).
- The compiler does not fix a slow algorithm or oversized lists.

For rollout details, benchmarks and escape hatches, read [React Compiler: A Production Guide](https://www.derar.dev/blog/react-compiler-production-guide-2026).

## Testing React 19 code

### Setup with Vitest and Testing Library

```bash
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
```

```ts
// vitest.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    setupFiles: ["./vitest.setup.ts"],
    globals: true,
  },
});
```

```ts
// vitest.setup.ts
import "@testing-library/jest-dom/vitest";
```

Recent versions of Testing Library require `@testing-library/dom` as an explicit peer dependency; install it alongside `@testing-library/react`. In React 19, `act` is imported from `react` (the `react-dom/test-utils` export is gone), though Testing Library wraps it for you.

### Testing a form action

```tsx
// signup-form.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { SignupForm } from "./signup-form";

describe("SignupForm", () => {
  it("shows field errors and keeps the typed email", async () => {
    const user = userEvent.setup();
    render(<SignupForm />);

    await user.type(screen.getByLabelText("Email"), "not-an-email");
    await user.type(screen.getByLabelText("Password"), "short");
    await user.click(screen.getByRole("button", { name: "Create account" }));

    expect(await screen.findByText("Enter a valid email address.")).toBeInTheDocument();
    expect(screen.getByLabelText("Email")).toHaveValue("not-an-email");
    expect(screen.getByLabelText("Email")).toBeInvalid();
  });

  it("shows pending state while the action is running", async () => {
    const user = userEvent.setup();
    render(<SignupForm />);

    await user.type(screen.getByLabelText("Email"), "ada@example.com");
    await user.type(screen.getByLabelText("Password"), "correct horse battery staple");
    await user.click(screen.getByRole("button", { name: "Create account" }));

    expect(screen.getByRole("button", { name: "Creating..." })).toBeDisabled();
    expect(await screen.findByRole("status")).toHaveTextContent("Account created");
  });
});
```

`findBy` queries wait for async updates; use them (not `getBy`) after actions. Mock the network at the boundary with MSW rather than mocking `fetch` per test:

```ts
// test/server.ts
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";

export const server = setupServer(
  http.post("/api/signup", async () => HttpResponse.json({ ok: true }, { status: 201 })),
);
```

### Testing optimistic UI

Make the server call controllable so you can assert the intermediate state:

```tsx
it("shows the todo immediately and keeps it after the server confirms", async () => {
  const user = userEvent.setup();
  let resolve!: () => void;
  const addTodo = vi.fn(() => new Promise<void>((r) => { resolve = r; }));

  render(<Todos todos={[]} addTodo={addTodo} />);
  await user.type(screen.getByLabelText("New task"), "Write tests");
  await user.click(screen.getByRole("button", { name: "Add" }));

  // optimistic row is visible while the promise is unresolved
  expect(await screen.findByText("Write tests")).toBeInTheDocument();

  await act(async () => resolve());
  expect(addTodo).toHaveBeenCalledWith("Write tests");
});
```

Import `act` from `react` and `vi` from `vitest` in the real file. Note that after the promise resolves, the optimistic row disappears unless the parent supplies the updated `todos`; a test with a stateful wrapper component asserts the full cycle.

### Testing components with `use`

Wrap in `Suspense` and use a resolved promise:

```tsx
it("renders comments from a promise", async () => {
  const promise = Promise.resolve([{ id: "1", author: "Ada", body: "Nice" }]);
  render(
    <Suspense fallback={<p>Loading</p>}>
      <Comments commentsPromise={promise} />
    </Suspense>,
  );
  expect(screen.getByText("Loading")).toBeInTheDocument();
  expect(await screen.findByText("Nice")).toBeInTheDocument();
});
```

### Server Components and Server Actions

Async Server Components are not supported by Testing Library's `render`. Test them by (1) extracting logic into plain async functions you unit test, (2) keeping client components thin and testing those with Testing Library, and (3) covering the integrated page with end-to-end tests in Playwright. See [Playwright End-to-End Testing: Reliable Suites, Fixtures, Auth and CI at Scale](https://www.derar.dev/blog/playwright-end-to-end-testing-reliable-ci-2026) and [Unit Testing with AI in 2026](https://www.derar.dev/blog/unit-testing-with-ai-2026). Test Server Actions as functions: call them with a `FormData` and assert the returned state, mocking the database layer.

```ts
import { describe, expect, it } from "vitest";
import { signup } from "./actions";

describe("signup action", () => {
  it("returns field errors for invalid input", async () => {
    const fd = new FormData();
    fd.set("email", "nope");
    fd.set("password", "short");
    const result = await signup({ ok: false }, fd);
    expect(result.ok).toBe(false);
    expect(result.fieldErrors?.email).toBeDefined();
  });
});
```

### Testing principles

- Query by role and accessible name; that doubles as an accessibility check.
- Assert on what the user sees, not on hook internals.
- Cover the three states of every action: pending, success, failure.
- Keep one end-to-end test per critical flow to cover framework wiring that unit tests cannot.

## Migrating from React 18

### The plan

1. **Upgrade to React 18.3 first.** It adds warnings for APIs removed in 19. Fix them while still on 18.
2. **Make sure you use the new JSX transform** (required in 19). Modern toolchains do.
3. **Run the official codemods.**

```bash
npx codemod@latest react/19/migration-recipe
npx types-react-codemod@latest preset-19 ./src
```

4. **Upgrade packages**: `react`, `react-dom`, `@types/react`, `@types/react-dom`. Check that libraries (UI kits, form libs, state libs) declare React 19 in peer dependencies; for stragglers, check their issue trackers and avoid `--force` installs without testing.
5. **Fix removed APIs** (table below).
6. **Run tests, then run the app with Strict Mode** and watch for new warnings.
7. **Adopt new features gradually**: Actions in new forms first, then refactor old ones.

### Removed and changed APIs

| React 18 | React 19 | Action |
| --- | --- | --- |
| `ReactDOM.render`, `hydrate`, `unmountComponentAtNode` | `createRoot`, `hydrateRoot`, `root.unmount()` | Migrate entry points |
| `propTypes` on components | Silently ignored | Use TypeScript |
| `defaultProps` on function components | Removed | Use default parameters |
| String refs | Removed | Use callback refs or `useRef` |
| Legacy Context (`contextTypes`) | Removed | Use `createContext` |
| `findDOMNode` | Removed | Use refs |
| `react-test-renderer/shallow` | Removed | Use Testing Library |
| `forwardRef` | Still works; `ref` is a prop | Migrate gradually |
| `<Context.Provider>` | `<Context>` works as provider | Optional |
| `useRef()` with no argument (TypeScript) | Argument required | `useRef<T>(null)` |
| `ReactElement["props"]` typed `any` | Typed `unknown` | Narrow or type the element |
| Global `JSX` namespace | Use `React.JSX` | Codemod handles it |
| UMD builds | Removed | Use ESM or a bundler |
| `react-dom/test-utils` `act` | `act` from `react` | Update imports |

### Behavior changes to watch

- **Errors**: uncaught errors in render are reported once via `window.reportError` rather than rethrown twice; update your error reporting accordingly.
- **Suspense**: siblings of a suspended component are not rendered until the boundary resolves (see the Suspense design section).
- **Strict Mode**: memoized results from the first render are reused during double rendering; double-invoked ref callbacks in development.
- **Transitions and form reset**: forms using actions reset uncontrolled inputs after success.
- **Third-party libraries** that read `element.ref` break: in React 19 you read `element.props.ref`.

### What not to rush

You do not need to rewrite every form to Actions. Start with new forms and forms that suffer from hand-rolled pending and error state. Keep working `onSubmit` handlers where they are.

## Common pitfalls

| Pitfall | Symptom | Fix |
| --- | --- | --- |
| Calling `useFormStatus` in the form's own component | `pending` never true | Move the hook into a child rendered inside the form |
| Creating the promise for `use` during client render | Endless suspense, warning about uncached promise | Create it in a Server Component, a cache or a library |
| Calling `useOptimistic` setter outside an Action | Dev warning; update flashes and reverts | Call inside `startTransition` or a form action |
| Form fields clear after a validation error | Automatic reset | Return `values` and use `defaultValue`, or use controlled inputs |
| Optimistic item disappears after success | Real state not updated | Update committed state (revalidate, setState) before the Action ends |
| Missing `name` on inputs | Empty `FormData` | Add `name` to each field |
| Relying on `form.submit()` | Action not triggered | Use `requestSubmit()` |
| Trusting hidden fields in Server Actions | Tampered IDs | Authorize on the server using the session |
| Returning non-serializable values from a Server Action | Runtime error | Return plain objects |
| Throwing for validation errors | Error boundary replaces the form | Return errors as state |
| Updating state after `await` inside a transition without wrapping | Update treated as urgent, flicker | Wrap in another `startTransition` |
| Spreading `ref` into DOM and also expecting `forwardRef` types | Type errors after upgrade | Use `React.ComponentProps` and accept `ref` as a prop |
| `useEffect` for data fetching in new code | Waterfalls, race conditions | Server Components, `use`, or TanStack Query |
| Wrapping the whole app in one Suspense boundary | Entire page flashes to fallback | Boundaries around independent regions |
| Multiple rapid Server Action calls expected to run in parallel | Sequential slowness | Use fetch or Server Components for reads; batch writes |
| Memoizing a promise with `useMemo` for `use` | Occasional refetch loops | Stable cache or library |
| Forgetting `key` on optimistic list items | Wrong item animations | Stable temporary ids |

## Performance and profiling

### Measure first

Use the React DevTools Profiler to record an interaction and read the flamegraph: which components rendered and why. React 19.2's Performance Tracks add scheduler and component tracks to the Chrome DevTools Performance panel, so you can see transitions, blocking work and component render times alongside the browser timeline (verify setup instructions in the React blog post for 19.2).

### Workflow

```text
1. Reproduce the slow interaction (type in the search box, switch tabs).
2. Record in React DevTools Profiler; enable "Record why each component rendered".
3. Identify the expensive commit: which component, how long, how often.
4. Decide the fix category:
     - Too many components re-render: let the React Compiler memoize; lift state down.
     - One component is heavy: split it, virtualize lists, move work to the server.
     - The main thread is blocked by a long render: useTransition or useDeferredValue.
     - Network latency: Suspense, prefetch, optimistic UI, cache.
5. Re-measure. Keep the change only if the numbers improve.
```

### Practical wins in a React 19 app

| Technique | Effect |
| --- | --- |
| Move data fetching to Server Components | Less client JavaScript, earlier data |
| Stream with Suspense | Faster first content |
| `useOptimistic` for common interactions | Perceived latency near zero |
| `useDeferredValue` for filter inputs | Typing stays responsive |
| Virtualize long lists (for example TanStack Virtual) | Constant DOM size |
| Split code at route and heavy widget level (`lazy`, dynamic import) | Smaller initial bundle |
| `Activity` (19.2) to keep hidden tabs mounted | Preserve state and avoid re-mount cost; verify behavior and memory trade-offs |
| React Compiler | Fewer wasted renders without manual memo |
| Avoid inline object creation in context values | Fewer consumer re-renders (compiler helps) |
| Use `preload` and `preconnect` for critical resources | Faster resource loading |

### Core Web Vitals link

Interaction to Next Paint (INP) improves when long renders are interruptible and when the UI responds immediately (optimistic updates, transitions). Track INP in the field with the `web-vitals` library and attribute slow interactions to components with the profiler.

## When NOT to use these features

- **Do not use `useOptimistic` for money movement** or irreversible operations. Wait for confirmation and show clear progress.
- **Do not convert every `onSubmit` to an Action** in a stable app with no pain. Migrate when you touch the form.
- **Do not use Server Actions as a general data API.** They are for mutations triggered by your own UI; they are sequential, tied to a framework and an unversioned internal protocol. Public or third-party consumers need a documented API.
- **Do not use `use(promise)` for client-created fetches** without a cache. Use TanStack Query or a framework loader.
- **Do not use transitions to fix slow network calls.** They are about render scheduling.
- **Do not skip validation on the server** because the client already validated.
- **Do not put the whole page in a client component** just to use a hook. Push `"use client"` down to the smallest interactive leaf.
- **Do not memoize everything by hand** if the compiler is on; remove stale `useMemo` and `useCallback` only after tests pass.
- **Do not assume progressive enhancement** if your form action is a client function. Without JavaScript it will not work.

## A step-by-step lab: build an optimistic comments feature

Goal: add a comment form with validation, pending state, optimistic display and accessible feedback, using a Server Action.

### Step 1: Schema and action

```ts
// app/posts/[id]/actions.ts
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

const schema = z.object({
  postId: z.uuid(),
  body: z.string().trim().min(2, "Write at least 2 characters.").max(1000, "Keep it under 1000 characters."),
});

export type CommentState = {
  status: "idle" | "success" | "error";
  message?: string;
  fieldErrors?: { body?: string[] };
  values?: { body: string };
};

export async function addComment(_prev: CommentState, formData: FormData): Promise<CommentState> {
  const session = await auth();
  if (!session) return { status: "error", message: "Sign in to comment." };

  const parsed = schema.safeParse({ postId: formData.get("postId"), body: formData.get("body") });
  if (!parsed.success) {
    return {
      status: "error",
      fieldErrors: z.flattenError(parsed.error).fieldErrors,
      values: { body: String(formData.get("body") ?? "") },
    };
  }

  await db.comment.create({ data: { postId: parsed.data.postId, body: parsed.data.body, authorId: session.user.id } });
  revalidatePath(`/posts/${parsed.data.postId}`);
  return { status: "success", message: "Comment posted." };
}
```

### Step 2: The client component

```tsx
// app/posts/[id]/comment-section.tsx
"use client";
import { useActionState, useOptimistic } from "react";
import { addComment, type CommentState } from "./actions";
import { SubmitButton } from "@/components/submit-button";

type Comment = { id: string; author: string; body: string; pending?: boolean };

export function CommentSection({ postId, comments, me }: { postId: string; comments: Comment[]; me: string }) {
  const [optimistic, addOptimistic] = useOptimistic(
    comments,
    (current: Comment[], body: string) => [...current, { id: `tmp-${current.length}`, author: me, body, pending: true }],
  );

  const [state, formAction] = useActionState(
    async (prev: CommentState, formData: FormData) => {
      addOptimistic(String(formData.get("body") ?? ""));
      return addComment(prev, formData);
    },
    { status: "idle" } as CommentState,
  );

  return (
    <section aria-labelledby="comments-h">
      <h2 id="comments-h">Comments ({optimistic.length})</h2>
      <ul>
        {optimistic.map((c) => (
          <li key={c.id} aria-busy={c.pending ? true : undefined}>
            <strong>{c.author}</strong>{c.pending ? " (sending)" : ""}: {c.body}
          </li>
        ))}
      </ul>

      <form action={formAction}>
        <input type="hidden" name="postId" value={postId} />
        <label htmlFor="body">Add a comment</label>
        <textarea
          id="body"
          name="body"
          rows={3}
          defaultValue={state.values?.body}
          aria-invalid={state.fieldErrors?.body ? true : undefined}
          aria-describedby={state.fieldErrors?.body ? "body-error" : undefined}
        />
        {state.fieldErrors?.body && <p id="body-error">{state.fieldErrors.body[0]}</p>}
        <SubmitButton pendingLabel="Posting...">Post comment</SubmitButton>
        <p role="status">{state.status === "success" ? state.message : null}</p>
        {state.status === "error" && state.message && <p role="alert">{state.message}</p>}
      </form>
    </section>
  );
}
```

### Step 3: Verify

1. Submit an empty comment: you should see the field error, and the text area keeps any typed text.
2. Submit a valid comment on a throttled network: the comment appears immediately with "(sending)", then settles into the real list after revalidation.
3. Make the action fail (stop the database): the optimistic comment disappears and an alert explains the failure.
4. Tab through the form with the keyboard and run a screen reader: label, error text, status messages.
5. Write the three tests from the testing section (validation, pending, optimistic) and one Playwright test for the whole flow.

## Short answers

**Is `useFormState` the same as `useActionState`?**
`useFormState` (from `react-dom`, in canary and early 19 builds) was renamed to `useActionState` (from `react`). Use `useActionState`.

**Can I use React Hook Form or Formik with Actions?**
Yes. They can call an action in their submit handler, or you can drop them for simple forms. For complex dynamic forms with deep validation and field arrays they are still valuable. Choose by form complexity, not fashion.

**Why does my promise passed to `use` keep refetching?**
It is recreated every render. Create it once (server, cache, library).

**Is `forwardRef` deprecated?**
It is still supported in 19, and `ref` as a prop is the recommended path. It is expected to be deprecated and removed in future major versions; use the codemod when convenient.

**Does React 19 work with my UI library?**
Check the library's React 19 support in its release notes or peer dependencies. Most major libraries (Radix, MUI, shadcn/ui components, TanStack) support it; verify the versions you use.

**How do I test Server Components?**
Unit test the data functions, test client components with Testing Library and cover the integration with end-to-end tests.

## Links worth keeping

- [React 19 release post](https://react.dev/blog/2024/12/05/react-19)
- [React 19 upgrade guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide)
- [React 19.2 release post](https://react.dev/blog/2025/10/01/react-19-2)
- [`useActionState` reference](https://react.dev/reference/react/useActionState)
- [`useOptimistic` reference](https://react.dev/reference/react/useOptimistic)
- [`use` reference](https://react.dev/reference/react/use)
- [`useFormStatus` reference](https://react.dev/reference/react-dom/hooks/useFormStatus)
- [`form` component reference](https://react.dev/reference/react-dom/components/form)
- [`useTransition` reference](https://react.dev/reference/react/useTransition)
- [Server Functions and `"use server"`](https://react.dev/reference/rsc/server-functions)
- [React Compiler documentation](https://react.dev/learn/react-compiler)
- [Testing Library: React](https://testing-library.com/docs/react-testing-library/intro/)
- [TanStack Query: Server rendering and hydration](https://tanstack.com/query/latest/docs/framework/react/guides/ssr)
- [Zod documentation](https://zod.dev)
- On this site: [Next.js Server Components, Caching and Data Patterns](https://www.derar.dev/blog/nextjs-server-components-caching-data-patterns-2026), [React Compiler: A Production Guide](https://www.derar.dev/blog/react-compiler-production-guide-2026), [Web Accessibility for Developers](https://www.derar.dev/blog/web-accessibility-wcag-developer-guide-2026), [Playwright End-to-End Testing](https://www.derar.dev/blog/playwright-end-to-end-testing-reliable-ci-2026), [Unit Testing with AI in 2026](https://www.derar.dev/blog/unit-testing-with-ai-2026)
