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.


_16
function NewsletterForm() {
_16
async function subscribe(formData: FormData) {
_16
const email = formData.get('email');
_16
await fetch('/api/subscribe', {
_16
method: 'POST',
_16
body: JSON.stringify({ email }),
_16
});
_16
}
_16
_16
return (
_16
<form action={subscribe}>
_16
<input type="email" name="email" required />
_16
<button type="submit">Subscribe</button>
_16
</form>
_16
);
_16
}

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.


_12
// app/newsletter/actions.ts
_12
'use server';
_12
_12
export async function subscribe(formData: FormData) {
_12
const email = String(formData.get('email') ?? '').trim();
_12
_12
if (!email.includes('@')) {
_12
return;
_12
}
_12
_12
await db.subscriber.create({ data: { email } });
_12
}


_11
// app/newsletter/page.tsx
_11
import { subscribe } from './actions';
_11
_11
export default function NewsletterPage() {
_11
return (
_11
<form action={subscribe}>
_11
<input type="email" name="email" required />
_11
<button type="submit">Subscribe</button>
_11
</form>
_11
);
_11
}

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:


_13
// app/posts/[id]/edit-form.tsx
_13
import { updatePost } from './actions';
_13
_13
export function EditForm({ postId }: { postId: string }) {
_13
const updateThisPost = updatePost.bind(null, postId);
_13
_13
return (
_13
<form action={updateThisPost}>
_13
<input name="title" />
_13
<button type="submit">Save</button>
_13
</form>
_13
);
_13
}


_10
// app/posts/[id]/actions.ts
_10
'use server';
_10
_10
export async function updatePost(postId: string, formData: FormData) {
_10
// postId comes from bind, formData from the form
_10
}

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.


_10
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.


_26
// app/signup/actions.ts
_26
'use server';
_26
_26
export type SignupState = {
_26
error?: string;
_26
success?: boolean;
_26
};
_26
_26
export async function signup(
_26
prevState: SignupState,
_26
formData: FormData
_26
): Promise<SignupState> {
_26
const email = String(formData.get('email') ?? '').trim();
_26
_26
if (!email.includes('@')) {
_26
return { error: 'Please enter a valid email address.' };
_26
}
_26
_26
const existing = await db.user.findUnique({ where: { email } });
_26
if (existing) {
_26
return { error: 'That email is already registered.' };
_26
}
_26
_26
await db.user.create({ data: { email } });
_26
return { success: true };
_26
}


_28
// app/signup/signup-form.tsx
_28
'use client';
_28
_28
import { useActionState } from 'react';
_28
import { signup, type SignupState } from './actions';
_28
_28
const initialState: SignupState = {};
_28
_28
export function SignupForm() {
_28
const [state, formAction, isPending] = useActionState(signup, initialState);
_28
_28
if (state.success) {
_28
return <p>Thanks for signing up.</p>;
_28
}
_28
_28
return (
_28
<form action={formAction}>
_28
<label htmlFor="email">Email</label>
_28
<input id="email" type="email" name="email" required />
_28
_28
{state.error && <p role="alert">{state.error}</p>}
_28
_28
<button type="submit" disabled={isPending}>
_28
{isPending ? 'Signing up...' : 'Sign up'}
_28
</button>
_28
</form>
_28
);
_28
}

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:


_14
// app/components/submit-button.tsx
_14
'use client';
_14
_14
import { useFormStatus } from 'react-dom';
_14
_14
export function SubmitButton({ children }: { children: React.ReactNode }) {
_14
const { pending } = useFormStatus();
_14
_14
return (
_14
<button type="submit" disabled={pending} aria-disabled={pending}>
_14
{pending ? 'Saving...' : children}
_14
</button>
_14
);
_14
}

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.


_10
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.


_41
// app/todos/todo-list.tsx
_41
'use client';
_41
_41
import { useOptimistic, useRef } from 'react';
_41
import { addTodo } from './actions';
_41
_41
type Todo = { id: string; text: string; pending?: boolean };
_41
_41
export function TodoList({ todos }: { todos: Todo[] }) {
_41
const formRef = useRef<HTMLFormElement>(null);
_41
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
_41
todos,
_41
(current: Todo[], text: string) => [
_41
...current,
_41
{ id: `temp-${current.length}`, text, pending: true },
_41
]
_41
);
_41
_41
async function formAction(formData: FormData) {
_41
const text = String(formData.get('text') ?? '');
_41
addOptimisticTodo(text);
_41
formRef.current?.reset();
_41
await addTodo(text);
_41
}
_41
_41
return (
_41
<>
_41
<ul>
_41
{optimisticTodos.map((todo) => (
_41
<li key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
_41
{todo.text}
_41
</li>
_41
))}
_41
</ul>
_41
<form action={formAction} ref={formRef}>
_41
<input name="text" required />
_41
<button type="submit">Add</button>
_41
</form>
_41
</>
_41
);
_41
}


_10
// app/todos/actions.ts
_10
'use server';
_10
_10
import { revalidatePath } from 'next/cache';
_10
_10
export async function addTodo(text: string) {
_10
await db.todo.create({ data: { text } });
_10
revalidatePath('/todos');
_10
}

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:


_21
'use client';
_21
_21
import { useTransition } from 'react';
_21
import { archiveProject } from './actions';
_21
_21
export function ArchiveButton({ projectId }: { projectId: string }) {
_21
const [isPending, startTransition] = useTransition();
_21
_21
return (
_21
<button
_21
disabled={isPending}
_21
onClick={() => {
_21
startTransition(async () => {
_21
await archiveProject(projectId);
_21
});
_21
}}
_21
>
_21
{isPending ? 'Archiving...' : 'Archive'}
_21
</button>
_21
);
_21
}

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.

_15
'use server';
_15
_15
export async function deletePost(postId: string) {
_15
const session = await getSession();
_15
if (!session) {
_15
throw new Error('Not signed in');
_15
}
_15
_15
const post = await db.post.findUnique({ where: { id: postId } });
_15
if (!post || post.authorId !== session.userId) {
_15
throw new Error('Not allowed');
_15
}
_15
_15
await db.post.delete({ where: { id: postId } });
_15
}

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.
#
file under:
React

Was this article helpful?

About the author

Danny Engineering

A software engineer with a strong belief in human-centric design and driven by a deep empathy for users. Combining the latest technology with human values to build a better, more connected world.