---
title: "Server Actions in React 19: forms, useActionState and useOptimistic"
description: "Learn how Server Actions work in React 19, from form actions and useActionState to pending UI with useFormStatus and instant feedback with useOptimistic."
url: https://www.danny.engineering/article/server-actions-in-react-19-forms-useactionstate-and-useoptimistic
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:25:00.000Z
tags: ["React"]
---

# Server Actions in React 19: forms, useActionState and useOptimistic

Handling a form in React used to involve a lot of ceremony. You kept every field in state, wrote an `onSubmit` handler that called `preventDefault`, sent a `fetch` to an API route you also had to write, then juggled loading flags, error messages and a reset once it worked.


React 19 replaces most of that with **actions**. You pass a function to a form's `action` prop, React calls it with the form data, and a small set of hooks handles pending states, results and optimistic updates. When that function runs on the server, it is a Server Action, and you no longer need a separate API endpoint at all.


This article is for developers who know React and want to understand how these pieces fit together. It uses Next.js App Router for the server examples, since it is the most common way to run Server Actions today, but the hooks are part of React itself.


## A quick note on naming


You will see two terms in the docs. A **Server Function** is any async function marked with `"use server"` that the client can call. When a Server Function is passed to a form's `action` prop or called from inside an action, React calls it a **Server Action**. The React docs switched to "Server Functions" as the umbrella term in late 2024, but "Server Actions" is still widely used, especially for forms. In this article they mean the same thing unless stated otherwise.


## Form actions: the basics


In React 19, the `action` prop on a `form` element accepts a function. React calls it with a `FormData` object when the form is submitted.


```typescript
function NewsletterForm() {
  async function subscribe(formData: FormData) {
    const email = formData.get('email');
    await fetch('/api/subscribe', {
      method: 'POST',
      body: JSON.stringify({ email }),
    });
  }

  return (
    <form action={subscribe}>
      <input type="email" name="email" required />
      <button type="submit">Subscribe</button>
    </form>
  );
}
```


A few things happen for you:

- There is no `preventDefault`. React handles the submission.
- The inputs are **uncontrolled**. You read values from `FormData` by their `name` instead of tracking each field in state.
- When the action finishes successfully, React **resets the form** automatically.
- The action runs inside a transition, so React knows the form is pending while it runs.

This works with a client-side function, as above. The real gain comes when the function runs on the server.


## Moving the action to the server


Add `"use server"` at the top of a file and every exported async function in it becomes a Server Function. The client gets a reference it can call, and the framework sends the request for you.


```typescript
// app/newsletter/actions.ts
'use server';

export async function subscribe(formData: FormData) {
  const email = String(formData.get('email') ?? '').trim();

  if (!email.includes('@')) {
    return;
  }

  await db.subscriber.create({ data: { email } });
}
```


```typescript
// app/newsletter/page.tsx
import { subscribe } from './actions';

export default function NewsletterPage() {
  return (
    <form action={subscribe}>
      <input type="email" name="email" required />
      <button type="submit">Subscribe</button>
    </form>
  );
}
```


The page is a Server Component, and the form works even before any JavaScript has loaded. The browser submits it as a normal form post and the framework runs the action. Once React hydrates, the same form submits without a full page reload. This is progressive enhancement for free.


You can also define a Server Function inline inside a Server Component by putting `"use server"` at the top of the function body. Keeping them in a separate `actions.ts` file tends to be easier to find and test, and it is the only option when you need to import them into a Client Component.


### Passing extra arguments


An action only receives the form data. To pass something else, such as an ID, use `bind`:


```typescript
// app/posts/[id]/edit-form.tsx
import { updatePost } from './actions';

export function EditForm({ postId }: { postId: string }) {
  const updateThisPost = updatePost.bind(null, postId);

  return (
    <form action={updateThisPost}>
      <input name="title" />
      <button type="submit">Save</button>
    </form>
  );
}
```


```typescript
// app/posts/[id]/actions.ts
'use server';

export async function updatePost(postId: string, formData: FormData) {
  // postId comes from bind, formData from the form
}
```


Arguments and return values cross the network, so they must be serialisable: strings, numbers, plain objects, arrays, dates, `FormData` and similar. You cannot pass a class instance or a function you expect to call on the server.


## Results and errors with useActionState


A bare form action has no way to tell the user what happened. `useActionState` fixes that. You give it an action and an initial state, and it gives you back the latest result, a wrapped action to pass to the form, and a pending flag.


```typescript
const [state, formAction, isPending] = useActionState(action, initialState);
```


The important difference is the action's signature. When used with `useActionState`, your action receives the **previous state** as its first argument and the form data second, and whatever it returns becomes the new state.


```typescript
// app/signup/actions.ts
'use server';

export type SignupState = {
  error?: string;
  success?: boolean;
};

export async function signup(
  prevState: SignupState,
  formData: FormData
): Promise<SignupState> {
  const email = String(formData.get('email') ?? '').trim();

  if (!email.includes('@')) {
    return { error: 'Please enter a valid email address.' };
  }

  const existing = await db.user.findUnique({ where: { email } });
  if (existing) {
    return { error: 'That email is already registered.' };
  }

  await db.user.create({ data: { email } });
  return { success: true };
}
```


```typescript
// app/signup/signup-form.tsx
'use client';

import { useActionState } from 'react';
import { signup, type SignupState } from './actions';

const initialState: SignupState = {};

export function SignupForm() {
  const [state, formAction, isPending] = useActionState(signup, initialState);

  if (state.success) {
    return <p>Thanks for signing up.</p>;
  }

  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input id="email" type="email" name="email" required />

      {state.error && <p role="alert">{state.error}</p>}

      <button type="submit" disabled={isPending}>
        {isPending ? 'Signing up...' : 'Sign up'}
      </button>
    </form>
  );
}
```


The form is a Client Component because it uses a hook, while the action still runs on the server. Returning errors as state, rather than throwing, keeps the user on the form with a helpful message. Save thrown errors for things that are genuinely unexpected and let an error boundary catch them.


`useActionState` also accepts an optional third argument, a permalink URL. Frameworks that support it use this to show the result if someone submits the form before JavaScript has loaded.


## Pending UI with useFormStatus


`isPending` from `useActionState` works well inside the component that owns the form. For a reusable submit button, `useFormStatus` from `react-dom` reads the status of the nearest parent form without any props:


```typescript
// app/components/submit-button.tsx
'use client';

import { useFormStatus } from 'react-dom';

export function SubmitButton({ children }: { children: React.ReactNode }) {
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending} aria-disabled={pending}>
      {pending ? 'Saving...' : children}
    </button>
  );
}
```


The one rule: `useFormStatus` must be called in a component **rendered inside** the form. Calling it in the same component that renders the `form` element will always report `pending` as false.


Besides `pending`, it also returns `data` (the `FormData` being submitted), `method` and `action`, which is handy for showing what is being saved.


## Instant feedback with useOptimistic


Some actions are slow, but the outcome is almost always success: liking a post, adding a comment, ticking off a task. Waiting for the server makes the interface feel sluggish. `useOptimistic` lets you show the expected result straight away and fall back to the real state when the action finishes.


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


You pass the real state and a function that merges an optimistic update into it. While an action is running, `optimisticState` includes your update. When the action completes and the real state changes, React switches back to it.


```typescript
// app/todos/todo-list.tsx
'use client';

import { useOptimistic, useRef } from 'react';
import { addTodo } from './actions';

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

export function TodoList({ todos }: { todos: Todo[] }) {
  const formRef = useRef<HTMLFormElement>(null);
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(
    todos,
    (current: Todo[], text: string) => [
      ...current,
      { id: `temp-${current.length}`, text, pending: true },
    ]
  );

  async function formAction(formData: FormData) {
    const text = String(formData.get('text') ?? '');
    addOptimisticTodo(text);
    formRef.current?.reset();
    await addTodo(text);
  }

  return (
    <>
      <ul>
        {optimisticTodos.map((todo) => (
          <li key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
            {todo.text}
          </li>
        ))}
      </ul>
      <form action={formAction} ref={formRef}>
        <input name="text" required />
        <button type="submit">Add</button>
      </form>
    </>
  );
}
```


```typescript
// app/todos/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function addTodo(text: string) {
  await db.todo.create({ data: { text } });
  revalidatePath('/todos');
}
```


The new todo appears immediately, slightly faded. When `addTodo` finishes, `revalidatePath` tells Next.js to refresh the page data, the parent passes down the real list, and the optimistic item is replaced by the saved one. If the action throws, the optimistic item simply disappears, because the real state never changed. Pair this with an error message so the user knows to try again.


One rule to remember: the function returned by `useOptimistic` must be called **inside an action or a transition**. Calling it from a plain event handler outside a transition produces a warning and the update will not behave as expected.


## Calling actions outside a form


Not every action is a form submission. To call a Server Function from a button click or another event, wrap it in `startTransition` so React tracks the pending state:


```typescript
'use client';

import { useTransition } from 'react';
import { archiveProject } from './actions';

export function ArchiveButton({ projectId }: { projectId: string }) {
  const [isPending, startTransition] = useTransition();

  return (
    <button
      disabled={isPending}
      onClick={() => {
        startTransition(async () => {
          await archiveProject(projectId);
        });
      }}
    >
      {isPending ? 'Archiving...' : 'Archive'}
    </button>
  );
}
```


You can also pass a function to a `button` element's `formAction` prop to give one form several submit buttons that do different things.


## Treat every Server Action as a public endpoint


This is the most important point in the article. A Server Function looks like an ordinary function in your code, but under the hood it is an HTTP endpoint that anyone can call with any arguments. Hiding the button in the UI does not stop someone sending the request directly.


Inside every action:

- **Check who is calling.** Read the session and confirm the user is signed in and allowed to do this specific thing.
- **Validate every input.** `FormData` values are strings typed by a user. Parse and check them, ideally with a schema library.
- **Do not trust bound arguments blindly.** An ID passed with `bind` still comes from the client side of the boundary. Confirm the user owns that record.
- **Return only what the client needs.** Whatever you return is sent to the browser.

```typescript
'use server';

export async function deletePost(postId: string) {
  const session = await getSession();
  if (!session) {
    throw new Error('Not signed in');
  }

  const post = await db.post.findUnique({ where: { id: postId } });
  if (!post || post.authorId !== session.userId) {
    throw new Error('Not allowed');
  }

  await db.post.delete({ where: { id: postId } });
}
```


## Version support

- **React 19** made actions, `useActionState`, `useFormStatus` and `useOptimistic` stable. React 19 was released in December 2024. Earlier canary builds used the name `useFormState`, which was renamed to `useActionState`; if you see the old name in a tutorial, it predates the stable release.
- **Server Functions** need a framework or bundler that supports React Server Components. Next.js App Router is the most common option. The Pages Router does not support them.
- **Next.js 15 and 16** ship with React 19, so all of the hooks in this article are available there.
- Client-side form actions (functions without `"use server"`) work in any React 19 app, with or without a server framework.

## When not to use it

- **Fetching data.** Server Functions are designed for mutations. In Next.js they are sent as POST requests and processed one at a time per client, so they are a poor fit for loading data. Fetch in Server Components instead.
- **Public APIs for other clients.** If a mobile app or third party needs to call your backend, build a proper Route Handler or API with a stable contract. Server Action endpoints are an implementation detail of your React app.
- **Highly interactive, field-by-field forms.** Live validation on every keystroke, dependent dropdowns and multi-step wizards may still need controlled inputs and client state. You can combine them with an action for the final submit.
- **Optimistic updates that often fail.** `useOptimistic` suits actions that nearly always succeed. If failure is common, showing a result and then taking it back is more confusing than a short wait.

## Wrapping up

- In React 19, a form's `action` prop accepts a function that receives `FormData`. React handles submission, pending state and the reset.
- Add `"use server"` to run that function on the server as a Server Action, with no API route needed and progressive enhancement included.
- Use `useActionState` to return results and validation errors, and `useFormStatus` inside the form for reusable pending buttons.
- Use `useOptimistic` to show likely results instantly, calling its update function inside an action or transition.
- Treat every Server Action as a public endpoint: check authentication, validate input and confirm ownership every time.

## Related reading

- [useActionState on react.dev](https://react.dev/reference/react/useActionState)
- [useOptimistic on react.dev](https://react.dev/reference/react/useOptimistic)
- [Server Functions on react.dev](https://react.dev/reference/rsc/server-functions)
