| | |

React Server Components 18 🧬 useActionState — Handling pending and error states in forms

⏱️ Estimated read: 18 min | |

useActionState is the hook that closes the loop between a Server Function and the UI that invokes it. Without it, a form with action={createPost} submits, mutates, and navigates, but the user sees no pending indicator, no validation message, and no confirmation. With it, the Server Function’s return value becomes component state, the pending boolean drives disabled states and labels, and validation errors render inline without a page reload. The hook is the difference between a form that works and a form that feels like an application.

The React documentation is precise about what the hook does: it “allows you to update state based on the result of a form action” . The action receives the previous state as its first argument, followed by the FormData. The hook returns a tuple of three values: the current state, a wrapped action to pass to the form, and a pending flag. The signature change—(prevState, formData) instead of (formData)—is the single most common source of confusion, because a Server Function written for a bare form action will receive the wrong argument order when wrapped .

Key point: useActionState makes the Server Function’s return value visible to the component. Known errors should be returned as state and displayed inline; unknown errors should be thrown and caught by the nearest error boundary. The hook does not distinguish between them—the developer does, by choosing return versus throw.


Why useActionState exists

The manual state boilerplate problem. Before React 19, a form with pending and error states required three separate useState calls: one for isLoading, one for error, and often one for data or success. The submit handler set isLoading(true), cleared the error, awaited the request, set the error or success, and set isLoading(false). This pattern appeared in every form, duplicated with slight variations, and each duplication introduced the possibility of a missed finally block or a stale error that persisted after a successful retry. useActionState collapses those three states into one managed lifecycle .

The progressive enhancement constraint. The hook is designed to work with Server Functions in a way that preserves progressive enhancement. If the form is submitted before JavaScript hydrates, React can still show the server’s response because the state is derived from the action’s return value, not from a client-side effect . This is why the hook is part of React itself rather than a framework abstraction—the behavior must work at the React level to survive the pre-hydration window.

The sequential queue. useActionState processes submissions one at a time. If the user clicks submit four times rapidly, the actions queue and execute sequentially, each receiving the previous action’s return value as its prevState . This is intentional: the hook’s contract requires knowing the previous state to compute the next one. The trade-off is that parallel mutations are not supported through this hook; if you need concurrency, you use useState and useTransition directly . For most form submissions, sequential is correct—it prevents race conditions and double-writes without any defensive code.

The error taxonomy. The hook draws a line between two kinds of failure. A validation error—”Title is required,” “Quantity not available”—is a known outcome that the action should return as part of its state. An unexpected error—a TypeError, a database connection failure—is a bug that should propagate to an error boundary. Throwing an error from the action cancels all queued actions and surfaces the nearest boundary . Returning an error populates state and keeps the form interactive. The developer chooses which path a given failure takes.


a. The signature change and the pending flag

The most immediate behavioral change when adopting useActionState is the action’s signature. A bare Server Function receives (formData). A function wrapped by useActionState receives (prevState, formData). The previous state is the last value the action returned, or the initial state on the first submission.

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

import { db } from '@/lib/db';
import { auth } from '@/lib/auth';

// The signature includes prevState as the first argument.
// Without useActionState, this would be (formData) only.
export async function updateProfile(
  prevState: { error: string | null; success: boolean },
  formData: FormData
) {
  const session = await auth();
  if (!session?.user) {
    // Unknown error: throw, let the boundary catch it.
    throw new Error('Unauthorized');
  }

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

  // Known validation error: return it as state.
  if (!name || name.trim().length === 0) {
    return { error: 'Name is required', success: false };
  }

  await db.user.update({
    where: { id: session.user.id },
    data: { name: name.trim() },
  });

  // Success: return the new state.
  return { error: null, success: true };
}
// app/profile/profile-form.tsx
'use client';

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

export function ProfileForm() {
  // The initial state matches the action's return shape.
  // The hook returns the current state, the wrapped action, and pending.
  const [state, formAction, pending] = useActionState(updateProfile, {
    error: null,
    success: false,
  });

  return (
    <form action={formAction}>
      <input name="name" disabled={pending} />

      {/* Known errors render inline from state. */}
      {state.error && <p className="error">{state.error}</p>}

      {/* Success feedback renders from the same state object. */}
      {state.success && <p className="success">Profile updated.</p>}

      {/* Pending drives the disabled state and the label. */}
      <button type="submit" disabled={pending}>
        {pending ? 'Saving…' : 'Save'}
      </button>
    </form>
  );
}

The pending flag is not merely a boolean for disabling a button. It is a signal that a transition is in flight, and it can be used to set aria-busy for accessibility, to dim the entire form, or to prevent navigation away from the page . The hook manages it automatically; the developer decides how prominently to surface it.


b. Known errors versus unknown errors

The error handling strategy is the most consequential design decision when using useActionState. Returning an error keeps the form alive and the state visible. Throwing an error unmounts the component and shows the boundary. The choice must match the nature of the failure.

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

export async function createComment(
  prevState: { error: string | null },
  formData: FormData
) {
  const body = formData.get('body') as string;

  // Validation failure: return, do not throw.
  if (!body || body.trim().length === 0) {
    return { error: 'Comment cannot be empty' };
  }

  // Business logic failure: return, do not throw.
  const post = await db.post.findUnique({ where: { id: formData.get('postId') as string } });
  if (!post) {
    return { error: 'Post not found' };
  }

  try {
    await db.comment.create({ data: { body: body.trim(), postId: post.id } });
    return { error: null };
  } catch (e) {
    // Unexpected database failure: throw to the boundary.
    // Returning here would hide a bug behind a generic message.
    throw new Error('Failed to create comment');
  }
}
// A form that distinguishes the two error types
'use client';

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

export function CommentForm() {
  const [state, formAction, pending] = useActionState(createComment, {
    error: null,
  });

  return (
    <form action={formAction}>
      <textarea name="body" disabled={pending} />

      {/* Validation errors from state render inline. */}
      {state.error && <p className="error">{state.error}</p>}

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

The React documentation states this distinction explicitly: “For known errors, such as ‘quantity not available’ validation errors from your backend, you can return it as part of your reducerAction state and display it in the UI. For unknown errors, such as undefined is not a function, you can throw an error” . The consequence of throwing is severe: React cancels all queued actions and rethrows the error from the hook, which means the form unmounts and the user loses their input . This is appropriate for a bug that should never have happened, and catastrophic for a validation message that the user could correct.


c. Combining useActionState with useOptimistic

useActionState manages the submission lifecycle; useOptimistic manages the immediate UI update. They are complementary, and the React documentation recommends using them together for forms where perceived latency matters .

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

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

interface Comment {
  id: string;
  body: string;
  pending?: boolean;
}

export function CommentSection({
  postId,
  initialComments,
}: {
  postId: string;
  initialComments: Comment[];
}) {
  const [state, formAction, pending] = useActionState(createComment, {
    error: null,
  });

  const [optimisticComments, addOptimistic] = 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.
    // This must happen synchronously before any await.
    addOptimistic({ id: `temp-${Date.now()}`, body, pending: true });

    // Invoke the wrapped action.
    formAction(formData);
  };

  return (
    <div>
      <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" disabled={pending} />
        {state.error && <p className="error">{state.error}</p>}
        <button type="submit" disabled={pending}>
          {pending ? 'Posting…' : 'Comment'}
        </button>
      </form>
    </div>
  );
}

The critical constraint is that addOptimistic must be called synchronously before the action’s first await. React’s transition system captures optimistic updates issued before the first suspension point; a call after an await will not be reverted correctly on failure . The pattern above satisfies this: addOptimistic runs, then formAction(formData) is invoked, and the action’s internal await happens after the optimistic update is registered.


Complete Example Session

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

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

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

interface ProfileState {
  error: string | null;
  success: boolean;
}

export async function updateProfile(
  prevState: ProfileState,
  formData: FormData
): Promise<ProfileState> {
  // Unknown errors (unauthorized) throw to the boundary.
  const session = await auth();
  if (!session?.user) {
    throw new Error('Unauthorized');
  }

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

  // Known validation errors return state.
  if (!name || name.trim().length < 2) {
    return { error: 'Name must be at least 2 characters', success: false };
  }

  try {
    await db.user.update({
      where: { id: session.user.id },
      data: { name: name.trim() },
    });
    revalidatePath('/profile');
    return { error: null, success: true };
  } catch (e) {
    // Unexpected database error: throw to the boundary.
    throw new Error('Failed to update profile');
  }
}

// ============================================
// PART 2: THE CLIENT FORM WITH PENDING AND ERROR
// ============================================

// app/profile/profile-form.tsx
'use client';

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

export function ProfileForm({ initialName }: { initialName: string }) {
  // Initial state must match the action's return shape.
  const [state, formAction, pending] = useActionState(updateProfile, {
    error: null,
    success: false,
  });

  return (
    <form action={formAction}>
      <label>
        Name
        <input name="name" defaultValue={initialName} disabled={pending} />
      </label>

      {/* Known errors render inline. */}
      {state.error && (
        <p role="alert" className="error">
          {state.error}
        </p>
      )}

      {/* Success feedback uses the same state object. */}
      {state.success && !state.error && (
        <p role="status" className="success">
          Profile updated.
        </p>
      )}

      <button type="submit" disabled={pending} aria-busy={pending}>
        {pending ? 'Saving…' : 'Save'}
      </button>
    </form>
  );
}

// ============================================
// PART 3: THE QUEUE BEHAVIOR (WHY PENDING PERSISTS)
// ============================================

// If the user clicks "Save" three times rapidly:
// 1. The first call runs with prevState = { error: null, success: false }.
// 2. The second call queues. It receives the first call's return value
//    as its prevState, not the initial state.
// 3. The third call queues behind the second.
//
// pending remains true until the last queued action settles.
// This is intentional: the hook needs the previous result to compute
// the next state, so it cannot run calls in parallel .

// ============================================
// PART 4: THE WRONG SIGNATURE (COMMON BUG)
// ============================================

// ❌ A Server Function written for a bare form action
export async function badAction(formData: FormData) {
  const name = formData.get('name'); // This works only without useActionState.
}

// ✅ When wrapped by useActionState, the signature must include prevState
export async function goodAction(prevState: any, formData: FormData) {
  const name = formData.get('name'); // formData is the second argument.
}

// The hook passes prevState as the first argument, shifting FormData to second.
// The TypeScript compiler catches this if the types are declared correctly.

// ============================================
// PART 5: THE PERMALINK PARAMETER (PROGRESSIVE ENHANCEMENT)
// ============================================

// useActionState accepts an optional third argument: permalink.
// On pages with dynamic content, this tells React where to navigate
// if the form submits before JavaScript loads .
//
// const [state, formAction, pending] = useActionState(
//   updateProfile,
//   initialState,
//   `/profile`  // permalink
// );
//
// After hydration, the permalink has no effect.
// Frameworks like Next.js typically handle this automatically.

// ============================================
// PART 6: RESETTING STATE
// ============================================

// useActionState does not provide a built-in reset.
// To clear a success message after a delay, use an effect:
'use client';

import { useEffect } from 'react';

export function ProfileFormWithReset({ initialName }: { initialName: string }) {
  const [state, formAction, pending] = useActionState(updateProfile, {
    error: null,
    success: false,
  });

  useEffect(() => {
    if (state.success) {
      // Clear the success message after 3 seconds.
      // This is a side effect of the state, not a state mutation.
      const timer = setTimeout(() => {
        // There is no dispatch for reset.
        // The recommended pattern is to navigate or re-render
        // with a new initial state. For a simple timer,
        // a separate useState flag works.
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [state.success]);

  return (
    <form action={formAction}>
      <input name="name" defaultValue={initialName} disabled={pending} />
      {state.error && <p className="error">{state.error}</p>}
      {state.success && <p className="success">Saved.</p>}
      <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
    </form>
  );
}

// ============================================
// PART 7: ARIA ATTRIBUTES FOR ACCESSIBILITY
// ============================================

// The pending flag enables proper accessibility attributes.
// aria-busy tells screen readers the form is processing.
// role="alert" announces errors immediately.
<button type="submit" disabled={pending} aria-busy={pending}>
  {pending ? 'Saving…' : 'Save'}
</button>

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

// ============================================
// PART 8: MULTIPLE ACTION TYPES (SWITCH PATTERN)
// ============================================

// When a form has multiple buttons that trigger different logic,
// pass a type identifier through the action.
export async function multiAction(
  prevState: { message: string | null },
  formData: FormData
) {
  const type = formData.get('_action') as string;

  switch (type) {
    case 'save':
      await db.save(formData);
      return { message: 'Saved' };
    case 'delete':
      await db.delete(formData);
      return { message: 'Deleted' };
    default:
      return { message: 'Unknown action' };
  }
}

// In the form, include hidden inputs or button names that set the type.
// <button name="_action" value="save">Save</button>
// <button name="_action" value="delete">Delete</button>

// ============================================
// PART 9: WHAT THROWING DOES TO THE QUEUE
// ============================================

// If the second queued action throws, the third is skipped.
// React cancels all subsequent queued actions when one throws.
// This is why known errors must return, not throw.
// A validation error that throws would silently drop the user's
// next submission attempt if they had clicked twice.

// ============================================
// PART 10: VERIFICATION CHECKLIST
// ============================================

// [ ] The action signature is (prevState, formData).
// [ ] The initial state matches the action's return type.
// [ ] Validation errors return state, not throw.
// [ ] Unexpected errors throw to the boundary.
// [ ] pending disables inputs and drives the button label.
// [ ] state.error renders with role="alert".
// [ ] state.success renders with role="status".
// [ ] The form works without JavaScript (progressive enhancement).

The ten parts covered the signature change, the pending flag, the error taxonomy, the queue behavior, the optimistic combination, and the accessibility attributes. The through-line is that useActionState is a lifecycle manager: it does not validate, it does not authorize, and it does not decide what is an error. It manages the state that the action returns and the pending flag while the action runs.


Quick Reference

Hook signature and return values

ElementTypeMeaning
action(prevState, formData) => Promise<State>The Server Function with the state-first signature
initialStateStateThe value before first submission
permalink (optional)stringURL for progressive enhancement before hydration
stateStateThe last returned value
formAction(formData) => voidThe wrapped action for the form
isPendingbooleanTrue while the action is in flight

Error strategy

Error typeMechanismResult
Validation failurereturn { error: '...' }Renders inline, form stays interactive
Business rule failurereturn { error: '...' }Renders inline, form stays interactive
Unexpected bugthrow new Error('...')Cancels queue, shows error boundary
Authentication failurethrow new Error('Unauthorized')Shows error boundary

useActionState vs useReducer

AspectuseReduceruseActionState
PurposeUI stateAction state
Side effectsNot allowedAllowed
ExecutionSynchronousSequential queue
Form integrationManualBuilt-in
Pending flagManualAutomatic

Best Practices

✅ Do This:

// Use the correct signature
async function action(prevState: State, formData: FormData) { ... }       // ✅

// Return validation errors as state
if (!name) return { error: 'Required', success: false };                  // ✅

// Throw unexpected errors
throw new Error('Database unavailable');                                  // ✅

// Disable inputs during pending
<input disabled={pending} />                                              // ✅

// Use role="alert" for errors
{state.error && <p role="alert">{state.error}</p>}                        // ✅

// Combine with useOptimistic for instant feedback
addOptimistic(data); formAction(formData);                                // ✅

❌ Don’t Do This:

// Use the bare form action signature
async function action(formData: FormData) { ... }                         // ❌

// Throw for validation errors
if (!name) throw new Error('Required');                                   // ❌

// Return raw database errors to the client
return { error: e.message };                                              // ❌ (leaks internals)

// Call formAction without startTransition
formAction(data);  // ❌ when called outside the action prop

// Expect parallel execution
// Queued actions run sequentially.                                        // ❌

Common Pitfalls

PitfallWhy It HappensFix
FormData is undefinedAction signature missing prevState(prevState, formData)
Pending never becomes trueformAction called manually without startTransitionWrap manual calls in startTransition
Error disappears on retryState not reset before new submissionReturn a fresh state object from every path
Queue skips submissionsAn earlier action threwCatch known errors and return them
Success message persistsNo reset mechanismUse a timer or navigate away
Optimistic update not revertedaddOptimistic called after awaitCall it synchronously before the action

Real-World Examples

1. Basic form with pending

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

2. Validation error return

if (!name) return { error: 'Name required', success: false };

3. Unexpected error throw

try { await db.update(); } catch { throw new Error('DB error'); }

4. Accessibility attributes

<button disabled={pending} aria-busy={pending}>Save</button>

5. Success message

{state.success && <p role="status">Saved.</p>}

6. Optimistic comment

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

7. Permalink for progressive enhancement

useActionState(action, initialState, '/profile')

8. Switch for multiple action types

switch (formData.get('_action')) { case 'save': ... }

9. Initial state matching return type

const initialState = { error: null, success: false };

10. Manual call with transition

startTransition(() => formAction(data));

Visual

The useActionState Lifecycle

┌──────────────────────────────────────────────────────────────┐
│  FROM SUBMIT TO RE-RENDER                                    │
│                                                              │
│  User submits form                                           │
│         │                                                    │
│         ▼                                                    │
│  ┌─────────────────┐                                        │
│  │ formAction      │  React wraps in a Transition          │
│  │ invoked         │  pending becomes true                  │
│  └────────┬────────┘                                        │
│           │                                                  │
│           ▼                                                  │
│  ┌─────────────────┐                                        │
│  │ Server Function │  Receives (prevState, formData)        │
│  │ executes        │                                        │
│  └────────┬────────┘                                        │
│           │                                                  │
│           ▼                                                  │
│  ┌─────────────────┐     ┌─────────────────┐               │
│  │ Returns state   │     │ Throws error    │               │
│  │                 │     │                 │               │
│  │ state updates   │     │ Queue cancelled │               │
│  │ pending = false │     │ Error boundary  │               │
│  │ form stays      │     │ shows           │               │
│  └─────────────────┘     └─────────────────┘               │
│                                                              │
│  The return value becomes state. The throw becomes a crash.  │
└──────────────────────────────────────────────────────────────┘

The Queue

┌──────────────────────────────────────────────────────────────┐
│  SEQUENTIAL EXECUTION                                        │
│                                                              │
│  Click 1 ──▶ Action 1 (prevState = initial)                 │
│                  │                                          │
│                  ▼                                          │
│              Returns state A                                │
│                  │                                          │
│  Click 2 ──▶ Action 2 (prevState = state A)                 │
│                  │                                          │
│                  ▼                                          │
│              Returns state B                                │
│                  │                                          │
│  Click 3 ──▶ Action 3 (prevState = state B)                 │
│                                                              │
│  pending remains true until the last action settles.        │
│  This is intentional: prevState requires the prior result.  │
│  For parallel mutations, do not use useActionState.        │
└──────────────────────────────────────────────────────────────┘

Error Taxonomy

┌──────────────────────────────────────────────────────────────┐
│  RETURN vs THROW                                             │
│                                                              │
│  RETURN                              THROW                   │
│  ┌────────────────────┐             ┌────────────────────┐  │
│  │ Validation error   │             │ Bug / unexpected   │  │
│  │ "Name required"    │             │ DB down            │  │
│  │                    │             │ Auth failure       │  │
│  │ state updates      │             │                    │  │
│  │ Form stays alive   │             │ Queue cancelled    │  │
│  │ User can correct   │             │ Boundary shows     │  │
│  │                    │             │ Form unmounts      │  │
│  └────────────────────┘             └────────────────────┘  │
│                                                              │
│  The user's input is recoverable only from the RETURN path.  │
│  Throw only for errors the user cannot fix.                  │
└──────────────────────────────────────────────────────────────┘

Combining with useOptimistic

┌──────────────────────────────────────────────────────────────┐
│  TWO HOOKS, TWO JOBS                                         │
│                                                              │
│  useActionState                  useOptimistic               │
│  ┌────────────────────┐         ┌────────────────────┐      │
│  │ state (error,      │         │ optimistic list    │      │
│  │  success)          │         │ addOptimistic      │      │
│  │ pending            │         │                    │      │
│  │ formAction         │         │ Immediate UI       │      │
│  │                    │         │ Auto-revert on     │      │
│  │ Lifecycle          │         │ failure            │      │
│  │ management         │         │                    │      │
│  └────────────────────┘         └────────────────────┘      │
│                                                              │
│  addOptimistic must be called synchronously before           │
│  formAction. After the first await, the optimistic           │
│  update is not captured by the transition.                   │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Hook signatureuseActionState(action, initialState, permalink?)
Return values[state, formAction, isPending]
Action signature(prevState, formData)
Known errorsReturn { error } in state
Unknown errorsThrow; reaches error boundary
Queue behaviorSequential; one action at a time
Progressive enhancementWorks with Server Functions before hydration
ResetNo built-in reset; navigate or manage with effects
Companion hookuseOptimistic for immediate UI

Key takeaways:

  • The signature shift is mandatory. A Server Function wrapped by useActionState receives (prevState, formData), not (formData). This is the most common adoption bug, and TypeScript catches it only if the types are declared explicitly .
  • Return for validation, throw for bugs. Known errors belong in state so the user can correct them. Unknown errors belong at the error boundary so they are not hidden. A thrown validation error destroys the user’s input and cancels queued submissions .
  • The queue is sequential by design. useActionState processes one submission at a time because it needs the previous result to compute the next state. This prevents race conditions but makes the hook unsuitable for genuinely parallel mutations. For those, use useState and useTransition directly .
  • Pending is a first-class accessibility signal. Use it to disable inputs, set aria-busy, and swap button labels. The hook manages the boolean; the developer decides how prominently to surface it .
  • useOptimistic covers the gap between submit and response. When the user should see their action reflected immediately, add the optimistic update synchronously before the action runs. The hook reverts it automatically if the action fails, but only if the call happened before the first await .

Remember: useActionState is a lifecycle manager, not a validation framework. It does not decide what is an error, what is a success, or what should be displayed. It receives the action’s return value, stores it as state, and toggles pending while the action runs. The decisions—what to return, what to throw, how to render the result—remain entirely with the developer. A form that uses the hook but returns raw database errors is still a form that leaks internals. A form that throws validation errors is still a form that crashes on bad input. The hook makes the mechanics invisible; the judgment stays visible.

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!