| | |

React Server Components 17 🧬 Form Actions — Wiring action props and progressive enhancement

⏱️ Estimated read: 19 min | |

The action prop on a <form> element is the oldest interface in HTML. It has always accepted a URL string. React 19 extends it to also accept a function. When that function is a Server Function—a function marked with "use server"—the form becomes progressively enhanced: it submits natively before JavaScript loads, and React intercepts the submission after hydration. The mechanics are invisible in the markup. The <form action={createPost}> looks like ordinary JSX. But the behavior underneath is a negotiation between the browser’s native form submission and React’s client runtime, and understanding that negotiation is what separates a form that works from a form that breaks in one of five specific ways.

The progressive enhancement claim is the one that deserves the most scrutiny. React’s documentation states that Server Functions passed to action props work without JavaScript. But “works” means something narrower than most developers assume. The form submits, the function executes, the mutation happens, and the response is a full page navigation. What does not happen without JavaScript is any client-side state update, any optimistic UI, any pending indicator, or any automatic form reset. Those require hydration. The enhancement is real but partial, and knowing which parts are which prevents the class of bugs where a form works in development (JavaScript enabled) and silently fails in a slow network scenario (JavaScript not yet loaded).

Key point: The action prop accepts a Server Function, which makes the form progressively enhanced. But the enhancement covers submission and mutation, not UI feedback. Pending states, optimistic updates, and error display all require client-side JavaScript and must be built separately.


Why the action prop changed

The manual fetch problem. Before React 19, submitting a form to a server function required onSubmit, event.preventDefault(), a fetch call, JSON.stringify, response parsing, and manual error handling. The action prop collapses that into a function reference. React handles the serialization, the request, and the response. The developer writes the function body, and the framework handles the transport.

The progressive enhancement requirement. A form with a URL action works without JavaScript because browsers have always submitted forms natively. React 19 preserves that behavior when the action is a Server Function. The form’s method defaults to POST, the encType defaults to multipart/form-data, and the browser submits the form to a React-generated endpoint. React replays the submission during hydration if it happened before the client runtime loaded. This is not a side effect; it is the design goal. The documentation lists it explicitly as a benefit .

The FormData contract. When a form is submitted to a Server Function, React passes the form’s FormData as the first argument. This is true both for the native submission and the hydrated one. The function receives the same shape of data in both cases, which is what makes the progressive enhancement transparent to the function author. The function does not need to know whether JavaScript was available.

The trade-off. The action prop is a submission interface, not a state management interface. It handles the mutation. It does not handle the pending spinner, the error message, the optimistic update, or the form reset. Those are the responsibility of useActionState, useFormStatus, useOptimistic, and the form’s own uncontrolled behavior. The directive solves the transport; the hooks solve the experience.


a. Wiring the action prop: Server Function vs URL

The action prop accepts three kinds of values: a URL string (the classic behavior), a Server Function reference (the React 19 behavior), and a function returned by useActionState (the enhanced behavior). The first two are the foundation; the third adds pending and error state.

// app/actions.ts
'use server';

import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { revalidatePath } from 'next/cache';

export async function createComment(formData: FormData) {
  // Authentication is required even though the form is rendered
  // by an authenticated page. The function is a public endpoint.
  const session = await auth();
  if (!session?.user) {
    throw new Error('Unauthorized');
  }

  const postId = formData.get('postId') as string;
  const body = formData.get('body') as string;

  // Validate before mutating.
  if (!body || body.trim().length === 0) {
    return { error: 'Comment cannot be empty' };
  }

  await db.comment.create({
    data: { postId, body, authorId: session.user.id },
  });

  // Invalidate the cached page so the new comment appears.
  revalidatePath(`/posts/${postId}`);
}
// app/posts/[id]/comment-form.tsx
import { createComment } from '@/app/actions';

export function CommentForm({ postId }: { postId: string }) {
  return (
    // The action prop receives the Server Function reference.
    // React sends the FormData to the function on submit.
    // Without JavaScript, the browser submits natively.
    <form action={createComment}>
      {/* Hidden fields are included in the FormData. */}
      <input type="hidden" name="postId" value={postId} />
      <textarea name="body" required />
      <button type="submit">Comment</button>
    </form>
  );
}

The hidden postId field is a deliberate choice that carries a security implication. Because the value is in the form, the client can modify it before submission. The Server Function must verify that the post exists and that the user is allowed to comment on it. The alternative—capturing the postId in a closure—removes the field from the form and binds the value into the function reference, which the client cannot modify without invalidating the reference.

// app/posts/[id]/comment-form.tsx — closure capture variant
import { createCommentForPost } from '@/app/actions';

export function CommentForm({ postId }: { postId: string }) {
  // Bind the postId to the action. The bound value is not a form field,
  // so it does not appear in the FormData and cannot be tampered with.
  const createComment = createCommentForPost.bind(null, postId);

  return (
    <form action={createComment}>
      <textarea name="body" required />
      <button type="submit">Comment</button>
    </form>
  );
}

The .bind(null, postId) pattern is the React documentation’s recommended way to pass additional arguments to a Server Function from a form action . The bound argument is serialized into the function reference, not into the form data. The function signature receives the bound argument first, then the FormData.


b. Progressive enhancement: what works without JavaScript

The progressive enhancement story has three parts: submission, mutation, and navigation. All three work without JavaScript. The parts that do not work are the client-side feedback mechanisms.

// app/posts/[id]/comment-form.tsx — bare form, no JS features
import { createComment } from '@/app/actions';

export function CommentForm({ postId }: { postId: string }) {
  return (
    <form action={createComment}>
      <input type="hidden" name="postId" value={postId} />
      <textarea name="body" required />
      {/* This button submits natively before hydration.
          The function runs. The page navigates.
          The textarea does not clear automatically. */}
      <button type="submit">Comment</button>
    </form>
  );
}

Without JavaScript, the browser performs a standard form submission. The method is POST, the enctype is multipart/form-data, and the target is a React-generated endpoint that maps to the Server Function. The function executes, the database is mutated, and the server responds with a redirect or a re-rendered page. The user sees a full page navigation, not a client-side transition. The form fields are not reset because there is no client runtime to reset them.

After hydration, React intercepts the submit event, prevents the native submission, serializes the FormData, sends it to the Server Function, and applies the result without a page reload. The form’s uncontrolled fields are reset automatically on success . The same function runs, but the experience changes.

The decision that follows from this is whether the form’s feedback requirements justify the client-side hooks. A comment form with a required field and a submit button works fine with progressive enhancement alone. A form with a pending state, an optimistic comment preview, and an inline error message needs useActionState and possibly useOptimistic. The directive does not choose for you.


c. Adding pending and error state with useActionState

useActionState wraps a Server Function and returns three values: the last returned state, an action function to pass to the form, and a pending boolean. The wrapped action is what makes the form show a spinner, disable the submit button, and display validation errors without a page reload.

// app/posts/[id]/comment-form.tsx
'use client';

import { useActionState } from 'react';
import { createComment } from '@/app/actions';

export function CommentForm({ postId }: { postId: string }) {
  // useActionState wraps the Server Function.
  // state: the last value returned by the function.
  // formAction: the wrapped function to pass to the form.
  // pending: true while the action is in flight.
  const [state, formAction, pending] = useActionState(createComment, null);

  return (
    <form action={formAction}>
      <input type="hidden" name="postId" value={postId} />
      <textarea name="body" required disabled={pending} />

      {/* The error is rendered only if the function returned one. */}
      {state?.error && <p className="error">{state.error}</p>}

      <button type="submit" disabled={pending}>
        {pending ? 'Posting…' : 'Comment'}
      </button>
    </form>
  );
}

The useActionState hook requires the Server Function to return a serializable value. The function above returns { error: string } on validation failure and undefined on success. The state variable reflects the most recent return value, and React re-renders the component when it changes. The pending boolean is true from the moment the form is submitted until the action settles, which is what makes the disabled state and the label swap work.

The hook also handles the error case where the function throws. If the Server Function throws, React surfaces the error to the nearest error boundary rather than populating state. This is the right behavior for unexpected failures—a thrown error is a bug, not a validation message. Validation failures should return a value, not throw.


Complete Example Session

// ============================================
// PART 1: THE SERVER ACTION
// ============================================

// app/actions.ts
'use server';

import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { revalidatePath } from 'next/cache';

export async function createComment(
  postId: string,
  formData: FormData
) {
  const session = await auth();
  if (!session?.user) {
    throw new Error('Unauthorized');
  }

  const body = formData.get('body') as string;

  if (!body || body.trim().length === 0) {
    return { error: 'Comment cannot be empty' };
  }

  if (body.length > 1000) {
    return { error: 'Comment must be under 1000 characters' };
  }

  await db.comment.create({
    data: { postId, body: body.trim(), authorId: session.user.id },
  });

  revalidatePath(`/posts/${postId}`);
  return { error: null };
}

// ============================================
// PART 2: BINDING A PARAMETER TO THE ACTION
// ============================================

// app/posts/[id]/page.tsx
import { createComment } from '@/app/actions';
import { CommentForm } from './comment-form';

export default async function PostPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;

  // Bind the postId as the first argument.
  // The bound value is part of the function reference, not the form data.
  const createCommentForPost = createComment.bind(null, id);

  return (
    <div>
      <h1>Post</h1>
      <CommentForm action={createCommentForPost} />
    </div>
  );
}

// ============================================
// PART 3: THE BARE FORM (PROGRESSIVE ENHANCEMENT ONLY)
// ============================================

// app/posts/[id]/comment-form.tsx
export function CommentForm({ action }: { action: (formData: FormData) => Promise<{ error: string | null }> }) {
  return (
    <form action={action}>
      <textarea name="body" required />
      <button type="submit">Comment</button>
    </form>
  );
}
// This form works before JavaScript loads.
// Submission, mutation, and navigation all function.
// It does not show pending state, does not clear the textarea,
// and does not display the returned error inline.

// ============================================
// PART 4: ADDING useActionState FOR PENDING AND ERRORS
// ============================================

// app/posts/[id]/comment-form.tsx
'use client';

import { useActionState } from 'react';

export function CommentForm({
  action,
}: {
  action: (formData: FormData) => Promise<{ error: string | null }>;
}) {
  const [state, formAction, pending] = useActionState(action, { error: null });

  return (
    <form action={formAction}>
      <textarea name="body" required disabled={pending} />
      {state.error && <p className="error">{state.error}</p>}
      <button type="submit" disabled={pending}>
        {pending ? 'Posting…' : 'Comment'}
      </button>
    </form>
  );
}

// ============================================
// PART 5: ADDING OPTIMISTIC UI WITH useOptimistic
// ============================================

// app/posts/[id]/comment-form.tsx
'use client';

import { useActionState, useOptimistic } from 'react';

export function CommentForm({
  action,
  initialComments,
}: {
  action: (formData: FormData) => Promise<{ error: string | null }>;
  initialComments: Comment[];
}) {
  const [state, formAction, pending] = useActionState(action, { error: null });

  // useOptimistic shows the comment immediately while the action is in flight.
  const [optimisticComments, addOptimisticComment] = useOptimistic(
    initialComments,
    (current, newComment: Comment) => [...current, newComment]
  );

  const handleSubmit = (formData: FormData) => {
    const body = formData.get('body') as string;
    // Add the optimistic comment before the action runs.
    addOptimisticComment({ id: 'temp', body, pending: true });
    // Then invoke the action.
    formAction(formData);
  };

  return (
    <>
      <ul>
        {optimisticComments.map(comment => (
          <li key={comment.id} style={{ opacity: comment.pending ? 0.5 : 1 }}>
            {comment.body}
          </li>
        ))}
      </ul>
      <form action={handleSubmit}>
        <textarea name="body" required disabled={pending} />
        {state.error && <p className="error">{state.error}</p>}
        <button type="submit" disabled={pending}>Comment</button>
      </form>
    </>
  );
}

// ============================================
// PART 6: useFormStatus FOR NESTED SUBMIT BUTTONS
// ============================================

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

import { useFormStatus } from 'react-dom';

export function SubmitButton() {
  // useFormStatus reads the status of the parent form.
  // It must be a child of the <form>, not the component that renders it.
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Submitting…' : 'Submit'}
    </button>
  );
}

// Usage:
// <form action={action}>
//   <input name="title" />
//   <SubmitButton />  {/* No props needed; status comes from context */}
// </form>

// ============================================
// PART 7: FORM RESET BEHAVIOR
// ============================================

// After a successful action, React resets uncontrolled form fields.
// This is automatic for forms with a Server Function action.
//
// If you need to control the reset, use a ref:
'use client';

import { useRef } from 'react';

export function ControlledForm({ action }: { action: (fd: FormData) => Promise<void> }) {
  const formRef = useRef<HTMLFormElement>(null);

  return (
    <form
      ref={formRef}
      action={async (formData) => {
        await action(formData);
        // The form resets automatically on success.
        // This line is only needed if you want to reset on a specific condition.
        formRef.current?.reset();
      }}
    >
      <input name="title" />
      <button type="submit">Submit</button>
    </form>
  );
}

// ============================================
// PART 8: PROGRESSIVE ENHANCEMENT VERIFICATION
// ============================================

// To verify the form works without JavaScript:
// 1. Build for production: npm run build
// 2. Start: npm run start
// 3. Open the page in a browser
// 4. Disable JavaScript in devtools
// 5. Submit the form
//
// Expected behavior:
// - The form submits natively (page navigation)
// - The Server Function runs (check the database)
// - The response is a full page
//
// Not expected without JavaScript:
// - Pending state on the button
// - Inline error messages
// - Textarea reset
// - Optimistic comment

// ============================================
// PART 9: THE ACTION PROP WITH A URL (CLASSIC BEHAVIOR)
// ============================================

// The action prop still accepts a URL string.
// This is the classic HTML behavior, unchanged by React 19.
export function SearchForm() {
  return (
    // GET submission: the browser appends the fields as query params.
    // This works without JavaScript and does not involve a Server Function.
    <form action="/search" method="get">
      <input type="search" name="q" />
      <button type="submit">Search</button>
    </form>
  );
}

// ============================================
// PART 10: WHAT BREAKS WITHOUT JAVASCRIPT
// ============================================

// A form that relies on client-side validation:
// <input type="text" pattern="[0-9]+" required />
// The browser enforces the pattern before submission.
// This works without JavaScript.
//
// A form that relies on a custom onClick handler:
// <button onClick={() => validate()}>Submit</button>
// Without JavaScript, the handler never runs.
// The form submits regardless of validation.
//
// A form with a stateful error display:
// {error && <p>{error}</p>}
// Without JavaScript, the error state never updates.
// The form submits, the action runs, the page navigates.

The ten parts covered the action prop’s two modes, the closure-capture pattern, the progressive enhancement boundary, the three hooks that add client-side feedback, and the verification steps. The through-line is that the form works without JavaScript at the submission level, and every additional piece of feedback is a client-side enhancement that must be built explicitly.


Quick Reference

Action prop value types

ValueBehaviorProgressive enhancement
URL stringClassic HTML form submissionYes (native)
Server Function referenceReact intercepts after hydrationYes (native before hydration)
Function from useActionStateAdds pending and error stateSubmission only

Hooks that enhance forms

HookReturnsUse case
useActionState(action, initialState)[state, formAction, pending]Inline errors and pending label
useFormStatus(){ pending, data, method, action }Submit button inside a nested component
useOptimistic(initial, reducer)[optimisticState, addOptimistic]Immediate UI update before the action settles

Progressive enhancement matrix

FeatureWithout JSWith JS
Form submissionYes (native)Yes (intercepted)
Server Function executionYesYes
MutationYesYes
Page navigationFull reloadClient transition
Pending stateNoYes
Inline errorsNoYes
Optimistic UINoYes
Form resetNoYes (automatic on success)

Binding patterns

PatternSyntaxClient can tamper?
Hidden input<input type="hidden" name="id" value={id} />Yes
Bound argumentaction.bind(null, id)No
Closure (inline)async function a(fd) { 'use server'; use(id); }No

Best Practices

✅ Do This:

// Pass the Server Function directly to action
<form action={createComment}>...</form>                              // ✅

// Bind server-side values to avoid hidden fields
const action = createComment.bind(null, postId);                     // ✅

// Use useActionState for inline error display
const [state, formAction, pending] = useActionState(action, null);   // ✅

// Disable inputs during pending to prevent double submits
<textarea disabled={pending} />                                      // ✅

// Verify the form works with JavaScript disabled
// Disable JS in devtools and submit                              // ✅

❌ Don’t Do This:

// Rely on client-side validation alone
<input pattern="[0-9]+" />  // ❌ Server must validate too

// Use onClick for form submission
<button onClick={submit}>   // ❌ No progressive enhancement

// Expect pending state without useActionState
<button type="submit">Save</button>  // ❌ No spinner without the hook

// Trust a hidden field for security-sensitive values
<input type="hidden" name="userId" />  // ❌ Client can change it

// Throw for validation errors
if (!body) throw new Error('Required');  // ❌ Use return instead

Common Pitfalls

PitfallWhy It HappensFix
Form does nothing without JSonSubmit used with preventDefaultUse action prop with a Server Function
Pending state never appearsuseActionState not usedWrap the action with the hook
Error message does not showFunction throws instead of returningReturn { error } for validation failures
Submit button shows wrong stateuseFormStatus used in the form componentMove it to a child component inside <form>
Hidden field value changedServer trusts client-provided IDBind the value or verify ownership
Double submissionButton not disabled during pendingDisable inputs with pending boolean

Real-World Examples

1. Bare form with Server Function

<form action={createPost}><input name="title" /><button>Save</button></form>

2. Bound action

const update = updatePost.bind(null, post.id);
<form action={update}><input name="title" /></form>

3. useActionState with pending

const [state, action, pending] = useActionState(create, null);
<button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>

4. useFormStatus in a nested button

function SaveButton() { const { pending } = useFormStatus(); return <button disabled={pending}>Save</button>; }

5. Optimistic comment

addOptimisticComment({ id: 'temp', body });
formAction(formData);

6. URL action for search

<form action="/search" method="get"><input name="q" /></form>

7. Validation return

if (!body) return { error: 'Required' };

8. Hidden field with ownership check

<input type="hidden" name="postId" value={postId} />
// Server: verify post.authorId === session.user.id

9. Form reset on success

// Automatic for forms with Server Function actions.
// Use a ref if you need conditional reset.

10. Disable inputs during pending

<textarea name="body" disabled={pending} />

Visual

The Action Prop’s Two Modes

┌──────────────────────────────────────────────────────────────┐
│  WHAT HAPPENS WHEN THE FORM SUBMITS                          │
│                                                              │
│  Without JavaScript                With JavaScript           │
│  ┌────────────────────┐           ┌────────────────────┐    │
│  │ Browser submits    │           │ React intercepts   │    │
│  │ natively to a      │           │ the submit event   │    │
│  │ React-generated    │           │                    │    │
│  │ endpoint           │           │ Prevents native    │    │
│  └─────────┬──────────┘           │ submission         │    │
│            │                       └─────────┬──────────┘    │
│            ▼                                 ▼               │
│  ┌────────────────────┐           ┌────────────────────┐    │
│  │ Server Function    │           │ Server Function    │    │
│  │ runs on server     │           │ runs on server     │    │
│  └─────────┬──────────┘           └─────────┬──────────┘    │
│            │                                 │               │
│            ▼                                 ▼               │
│  ┌────────────────────┐           ┌────────────────────┐    │
│  │ Full page reload   │           │ Client transition  │    │
│  │ No pending state   │           │ Pending state      │    │
│  │ No error display   │           │ Inline errors      │    │
│  │ No form reset      │           │ Form reset         │    │
│  └────────────────────┘           └────────────────────┘    │
│                                                              │
│  Same function. Same mutation. Different experience.         │
└──────────────────────────────────────────────────────────────┘

The Three Hooks

┌──────────────────────────────────────────────────────────────┐
│  EACH HOOK SOLVES ONE PROBLEM                                │
│                                                              │
│  useActionState          useFormStatus       useOptimistic   │
│  ┌────────────────┐     ┌────────────────┐  ┌─────────────┐ │
│  │ state          │     │ pending        │  │ optimistic  │ │
│  │ formAction     │     │ data           │  │ state       │ │
│  │ pending        │     │ method         │  │ addOptimistic│ │
│  │                │     │ action         │  │             │ │
│  │ Inline errors  │     │ Submit button  │  │ Instant UI  │ │
│  │ Pending label  │     │ inside form    │  │ before      │ │
│  │                │     │                │  │ action runs │ │
│  └────────────────┘     └────────────────┘  └─────────────┘ │
│                                                              │
│  Use all three for a complete form experience.               │
└──────────────────────────────────────────────────────────────┘

Binding vs Hidden Field

┌──────────────────────────────────────────────────────────────┐
│  WHERE THE VALUE LIVES                                       │
│                                                              │
│  Hidden Field                Bound Argument                  │
│  ┌────────────────────┐      ┌────────────────────┐         │
│  │ <input type="hidden"│      │ action.bind(null, id)       │
│  │ name="id"           │      │                    │         │
│  │ value={id} />       │      │ The value is in    │         │
│  │                     │      │ the function       │         │
│  │ The value is in     │      │ reference          │         │
│  │ the form data       │      │                    │         │
│  └─────────┬──────────┘      └─────────┬──────────┘         │
│            │                            │                    │
│            ▼                            ▼                    │
│  Client can modify            Client cannot modify          │
│  (must verify on server)      (tamper invalidates reference)│
│                                                              │
│  Use binding for security-sensitive values.                  │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
action prop acceptsURL string, Server Function, useActionState wrapper
Default method for Server FunctionPOST
Default encodingmultipart/form-data
Form argumentFormData (automatically passed)
Bound argument positionBefore the FormData
Progressive enhancementSubmission and mutation work without JS
No JS: pending stateNot available
No JS: inline errorsNot available
No JS: form resetNot available
Hooks for enhancementuseActionState, useFormStatus, useOptimistic

Key takeaways:

  • The action prop with a Server Function is the progressive enhancement baseline. The form submits natively, the function runs, and the mutation happens even before JavaScript loads. Everything beyond that—pending states, errors, optimistic updates—is a client-side enhancement that must be built explicitly.
  • Binding is safer than hidden fields. A bound argument (action.bind(null, id)) is part of the function reference and cannot be modified by the client. A hidden input is form data and can be changed before submission. Use binding for values the server must trust, and verify ownership even when binding.
  • useActionState is the standard wrapper for forms that need feedback. It provides the pending boolean, the last returned state, and the wrapped action. The Server Function must return validation errors rather than throw them, because thrown errors go to the error boundary, not to state.
  • useFormStatus is for nested submit buttons. It reads the status of the parent form from context. It must be called in a component that is rendered inside the <form>, not in the component that renders the form.
  • React resets uncontrolled form fields after a successful action. This is automatic for forms with Server Function actions. If the reset needs to be conditional, use a ref and call reset() manually.

Remember: The form action is the intersection of two worlds. On one side is HTML’s native submission model, which has worked for thirty years and requires no JavaScript. On the other is React’s client runtime, which can intercept, serialize, and replay. The Server Function is the bridge: it receives FormData in both cases and runs the same mutation. The enhancement is the negotiation between the two—and the parts of the experience that require JavaScript are exactly the parts that cannot exist without it. Build the form so it works without JavaScript, then layer the client-side feedback on top. The baseline is a form that submits. The enhancement is a form that feels instant.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!