TExcelTAD
Home › React › React 19 Actions

React 19 Actions

Submitting data is one of the most common things an app does: post a comment, save a profile, add to cart. Each time you need the same plumbing — a pending flag, error handling, disabling the button, resetting the form. React 19 builds this in. An Action is an async function run inside a transition, and React tracks its pending state, errors and optimistic updates for you.

API Purpose
<form action={fn}> calls fn(formData) on submit, as an Action; resets the form afterwards
useActionState(action, initial) returns [state, formAction, isPending]; state is what the action returned last
useFormStatus() lets a child (e.g. a submit button) read its parent form's pending state
useOptimistic(state, update) shows a temporary optimistic value while an Action runs
use(resource) reads a promise or context; may be called conditionally

The "server" in these examples is simulated with setTimeout.

Forms with an action function

Pass a function to the form's action prop. React calls it with a FormData object — no preventDefault, no onSubmit:

jsx · try it yourself
import { useState } from 'react';

const wait = (ms) => new Promise((r) => setTimeout(r, ms));

export default function App() {
  const [guests, setGuests] = useState(['Hien']);

  async function addGuest(formData) {
    const name = formData.get('name').trim();
    if (!name) return;
    await wait(600);                 // pretend to save on the server
    setGuests((g) => [...g, name]);
  }

  return (
    <div>
      <form action={addGuest}>
        <input name="name" placeholder="Guest name" />
        <button>Add guest</button>
      </form>
      <ul>{guests.map((g) => <li key={g}>{g}</li>)}</ul>
      <small>Notice the input is cleared automatically after a successful submit.</small>
    </div>
  );
}

useActionState: result, errors and pending

useActionState wraps an action so that whatever it returns becomes state — perfect for validation messages and results. Your action receives the previous state as the first argument and the form data as the second:

jsx · try it yourself
import { useActionState } from 'react';

const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const TAKEN = ['admin', 'root', 'react'];

async function register(prevState, formData) {
  const username = formData.get('username').trim().toLowerCase();
  await wait(800);
  if (username.length < 3) return { ok: false, message: 'Username must be at least 3 characters.', attempts: prevState.attempts + 1 };
  if (TAKEN.includes(username)) return { ok: false, message: `"${username}" is already taken.`, attempts: prevState.attempts + 1 };
  return { ok: true, message: `Welcome aboard, ${username}! 🎉`, attempts: prevState.attempts + 1 };
}

export default function App() {
  const [state, formAction, isPending] = useActionState(register, { ok: null, message: '', attempts: 0 });

  return (
    <form action={formAction} style={{ width: 320 }}>
      <input name="username" placeholder="Pick a username (try 'admin')" disabled={isPending} />{' '}
      <button disabled={isPending}>{isPending ? 'Checking…' : 'Register'}</button>
      {state.message && <p style={{ color: state.ok ? 'green' : 'crimson' }}>{state.message}</p>}
      <small>Attempts: {state.attempts}</small>
    </form>
  );
}

There's no useState, no try/finally to reset a loading flag, and no stale-closure trouble: React passes in the latest state every time.

useFormStatus: smart submit buttons

A reusable submit button often needs to know whether its form is submitting. Instead of passing isPending down as a prop, call useFormStatus in a component rendered inside the form:

jsx · try it yourself
import { useFormStatus } from 'react-dom';
import { useState } from 'react';

function SubmitButton({ children }) {
  const { pending, data } = useFormStatus();
  return (
    <button disabled={pending} style={{ minWidth: 140 }}>
      {pending ? `Sending "${data.get('message')}"…` : children}
    </button>
  );
}

const wait = (ms) => new Promise((r) => setTimeout(r, ms));

export default function App() {
  const [sent, setSent] = useState([]);

  async function send(formData) {
    await wait(1000);
    setSent((s) => [...s, formData.get('message')]);
  }

  return (
    <div>
      <form action={send}>
        <input name="message" defaultValue="Hello!" />{' '}
        <SubmitButton>Send</SubmitButton>
      </form>
      <ul>{sent.map((m, i) => <li key={i}>✉️ {m}</li>)}</ul>
    </div>
  );
}

Note: useFormStatus is imported from react-dom and only reports on the parent <form>. Calling it in the same component that renders the form won't work.

useOptimistic: instant feedback

Users shouldn't stare at a spinner when you can predict the result. useOptimistic shows a temporary value immediately while the Action runs; when it finishes, React switches back to the real state:

jsx · try it yourself
import { useOptimistic, useState, startTransition } from 'react';

const wait = (ms) => new Promise((r) => setTimeout(r, ms));
let attempt = 0;

async function saveMessage(text) {
  await wait(1200);
  attempt += 1;
  if (attempt % 3 === 0) throw new Error('Server error (every 3rd message fails)');
  return { id: attempt, text };
}

export default function App() {
  const [messages, setMessages] = useState([{ id: 0, text: 'Welcome to the chat!' }]);
  const [error, setError] = useState('');
  const [optimistic, addOptimistic] = useOptimistic(messages, (current, text) => [
    ...current,
    { id: `temp-${text}`, text, sending: true },
  ]);

  async function send(formData) {
    const text = formData.get('text');
    if (!text) return;
    setError('');
    addOptimistic(text);
    try {
      const saved = await saveMessage(text);
      startTransition(() => setMessages((m) => [...m, saved]));
    } catch (err) {
      setError(`"${text}" was not sent: ${err.message}`);
    }
  }

  return (
    <div style={{ width: 320 }}>
      <ul style={{ listStyle: 'none', padding: 0 }}>
        {optimistic.map((m) => (
          <li key={m.id} style={{ opacity: m.sending ? 0.5 : 1 }}>
            💬 {m.text} {m.sending && <small>(sending…)</small>}
          </li>
        ))}
      </ul>
      <form action={send}>
        <input name="text" placeholder="Message" autoComplete="off" /> <button>Send</button>
      </form>
      {error && <p style={{ color: 'crimson' }}>{error}</p>}
    </div>
  );
}

When the third message fails, the optimistic entry simply disappears (the real state never got it) and an error is shown.

The use hook

use reads a resource during render. With a promise, it suspends until the value is ready (see Suspense & lazy). With a context, it works like useContext — but unlike other hooks, use may be called inside conditions and loops:

jsx
function Price({ show }) {
  if (!show) return null;
  const currency = use(CurrencyContext);   // ✅ allowed after an early return
  return <span>{currency}</span>;
}

Before and after

Task Before React 19 With Actions
pending state useState + try/finally isPending / useFormStatus
reading inputs controlled state or e.target formData.get('name')
errors & results extra state variables return them from the action
reset form manual setX('') automatic for <form action>
instant feedback manual temp state + rollback useOptimistic

Tip: In frameworks that support Server Functions (marked with 'use server'), the same <form action={…}> can call code that runs on the server, and the form even works before JavaScript loads.

Test yourself

What does useActionState return?

  1. [state, setState]
  2. [state, formAction, isPending]
  3. { data, error }
  4. A promise

Where must useFormStatus be called to see a form's pending state?

  1. In the component that renders the <form>
  2. In a component rendered inside the <form>
  3. Anywhere in the app
  4. Only in the action function

What happens to an optimistic value from useOptimistic when the action finishes?

  1. It is saved permanently
  2. React goes back to the real state, which you should have updated if successful
  3. It is converted to an error
  4. The page reloads