Skip to content
jshacks.dev
Frameworks

Handle form actions with useActionState

Run a form action with React 19 useActionState to get the last result and a pending flag, without writing onSubmit and loading state by hand.

1 min read
Summarize in AI

Form handling usually means preventing default, tracking pending and storing the error. React 19 lets a form take a function as its action, and useActionState keeps the result.

src/Subscribe.jsxJSX
import { useActionState } from 'react';
import { subscribe } from './api.js';

async function subscribeAction(previousState, formData) {
  const email = formData.get('email');
  if (!email.includes('@')) {
    return { ok: false, message: 'Enter a valid email address' };
  }
  await subscribe(email);
  return { ok: true, message: `Subscribed ${email}` };
}

export function Subscribe() {
  const [state, formAction, isPending] = useActionState(subscribeAction, null);

  return (
    <form action={formAction}>
      <input name="email" type="text" />
      <button disabled={isPending}>Subscribe</button>
      {state && <p>{state.message}</p>}
    </form>
  );
}
Text
(submit "nope")          -> Enter a valid email address
(submit "[email protected]")  -> Subscribed [email protected]

React calls the action with the previous state and the form's FormData. Whatever it returns becomes the new state, and isPending is true until the promise settles. The form also resets itself after a successful action. See useActionState.

In React 19 this hook replaces useFormState from react-dom. Keep it for forms, and use plain state for values not tied to a submit.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.