This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: react-19-use-action-state-and-optimistic-guardrail

React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers

Enforces native React 19 Action primitives (useActionState, useOptimistic, useFormStatus) for mutations and async form submissions. Prohibits manual useState submit wrappers, manual loading states, and synthetic event prevention (e.preventDefault()) that disrupt concurrent transitions and break native progressive enhancement.

Prohibited Anti-Pattern: Manual onSubmit State Orchestration with useState Pending/Error Flags and Imperative Rollbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers - Enforces native React 19 Action primitives (useActionState, useOptimistic, useFormStatus) for mutations and async form submissions. Prohibits manual useState submit wrappers, manual loading states, and synthetic event prevention (e.preventDefault()) that disrupt concurrent transitions and break native progressive enhancement.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}, components/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-19-use-action-state-and-optimistic-guardrail"
---

# React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Manual onSubmit State Orchestration with useState Pending/Error Flags and Imperative Rollbacks

## System Constraints
You are a Principal Software Architect enforcing React 19 enterprise standards. Mandate the strict adoption of React 19 Action hooks (useActionState, useOptimistic, useFormStatus) for all asynchronous user interactions, data mutations, and forms. Reject legacy React 18 patterns including manual isSubmitting/isLoading flags, manual try/catch error state tracking, and redundant e.preventDefault() form handlers.

## Strict Guidelines
- Engineers MUST use 'useActionState' instead of manual 'useState' bundles (isLoading, error, data) for executing mutations and async form actions.
- Action handler functions passed to 'useActionState' MUST accept '(previousState, formData)' as standard parameters and return a predictable immutable state object.
- Engineers MUST NOT hijack form submission via 'onSubmit={handleSubmit}' with 'e.preventDefault()' when the operation is an async data mutation; bind the action directly to '<form action={formAction}>' or submit buttons via 'formAction'.
- Engineers MUST use 'useOptimistic' for rendering speculative UI changes; manual setState mutations paired with imperative try/catch rollbacks are strictly forbidden.
- Components rendering submit buttons or pending indicators nested within forms MUST consume 'useFormStatus' rather than prop-drilling pending flags from parent components.
- Engineers MUST ensure optimistic updates automatically revert upon rejected action promises by driving optimistic transitions through the action dispatcher returned by useActionState or startTransition.
- Server and client actions MUST throw or return serializable structured error payloads conforming to your application's domain error contracts.

## Bad vs Good Implementations
### Form Mutation: useActionState vs Manual useState Wrapper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Employs an imperative onSubmit event listener with e.preventDefault(), spreading mutation state across three separate useState hooks (name, loading, error). Fails to leverage React 19 concurrent transitions and prevents child components from accessing pending status.
```typescript
import React, { useState } from 'react';

interface UserProfile {
  name: string;
}

export function EditProfile({ initialName }: { initialName: string }) {
  const [name, setName] = useState(initialName);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // ANTI-PATTERN: Manual async wrapper, e.preventDefault(), fragmented states
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/profile', {
        method: 'POST',
        body: JSON.stringify({ name }),
      });
      if (!res.ok) throw new Error('Update failed');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button type="submit" disabled={loading}>
        {loading ? 'Saving...' : 'Save'}
      </button>
      {error && <p className="error">{error}</p>}
    </form>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to React 19 standards: updates are driven by 'useActionState' with a declarative action signature (prevState, formData). Nested 'SubmitButton' manages its pending state via 'useFormStatus', enabling automatic concurrency handling and eliminating manual state glue.
```typescript
import React, { useActionState } from 'react';
import { useFormStatus } from 'react-dom';

interface ActionState {
  data: { name: string } | null;
  error: string | null;
}

async function updateProfile(
  _prevState: ActionState,
  formData: FormData
): Promise<ActionState> {
  const newName = formData.get('name') as string;
  try {
    const res = await fetch('/api/profile', {
      method: 'POST',
      body: JSON.stringify({ name: newName }),
    });
    if (!res.ok) throw new Error('Update failed');
    return { data: { name: newName }, error: null };
  } catch (err: unknown) {
    return {
      data: null,
      error: err instanceof Error ? err.message : 'Unknown error',
    };
  }
}

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving...' : 'Save'}
    </button>
  );
}

export function EditProfile({ initialName }: { initialName: string }) {
  const [state, formAction] = useActionState(updateProfile, {
    data: { name: initialName },
    error: null,
  });

  return (
    <form action={formAction}>
      <input name="name" defaultValue={state.data?.name ?? initialName} />
      <SubmitButton />
      {state.error && <p className="error">{state.error}</p>}
    </form>
  );
}
```

### Optimistic UI: useOptimistic vs Manual Mutation & Imperative Rollback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Performs manual optimistic mutations by stashing previous states and reverting inside catch blocks. This pattern causes tearing, race conditions when multiple requests overlap, and memory leaks if mutations complete out-of-order.
```typescript
import React, { useState } from 'react';

interface Comment {
  id: string;
  text: string;
}

export function CommentList({ initialComments }: { initialComments: Comment[] }) {
  const [comments, setComments] = useState<Comment[]>(initialComments);
  const [error, setError] = useState<string | null>(null);

  // ANTI-PATTERN: Imperative snapshot, manual state mutation, and manual try/catch rollback
  const handleAddComment = async (text: string) => {
    const previousComments = [...comments];
    const tempComment = { id: 'temp-' + Date.now(), text };
    
    setComments((prev) => [...prev, tempComment]);
    
    try {
      const res = await fetch('/api/comments', {
        method: 'POST',
        body: JSON.stringify({ text }),
      });
      if (!res.ok) throw new Error('Failed to post comment');
      const confirmedComment: Comment = await res.json();
      setComments((prev) =>
        prev.map((c) => (c.id === tempComment.id ? confirmedComment : c))
      );
    } catch (err: unknown) {
      // Rollback manually on error
      setComments(previousComments);
      setError('Failed to post comment');
    }
  };

  return (
    <div>
      {error && <p className="error">{error}</p>}
      <ul>
        {comments.map((c) => (
          <li key={c.id}>{c.text}</li>
        ))}
      </ul>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Implements 'useOptimistic' paired with 'useActionState'. Speculative states are automatically scoped to the transition lifecycle; if the action promise rejects, React automatically discards the optimistic state and re-renders the base state without manual rollback plumbing.
```typescript
import React, { useActionState, useOptimistic } from 'react';

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

async function postCommentAction(
  prevComments: Comment[],
  formData: FormData
): Promise<Comment[]> {
  const text = formData.get('comment') as string;
  const res = await fetch('/api/comments', {
    method: 'POST',
    body: JSON.stringify({ text }),
  });
  if (!res.ok) {
    throw new Error('Failed to post comment');
  }
  const newComment: Comment = await res.json();
  return [...prevComments, newComment];
}

export function CommentList({ initialComments }: { initialComments: Comment[] }) {
  const [comments, formAction] = useActionState(postCommentAction, initialComments);

  const [optimisticComments, addOptimisticComment] = useOptimistic(
    comments,
    (current, newText: string): Comment[] => [
      ...current,
      { id: 'temp-' + Date.now(), text: newText, pending: true },
    ]
  );

  async function handleAction(formData: FormData) {
    const text = formData.get('comment') as string;
    addOptimisticComment(text);
    await formAction(formData);
  }

  return (
    <div>
      <form action={handleAction}>
        <input name="comment" required />
        <button type="submit">Post Comment</button>
      </form>
      <ul>
        {optimisticComments.map((c) => (
          <li key={c.id} style={{ opacity: c.pending ? 0.6 : 1.0 }}>
            {c.text} {c.pending && '(sending...)'}
          </li>
        ))}
      </ul>
    </div>
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers

React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers defines an industrial-grade behavioral standard for frontend engineering. Enforces native React 19 Action primitives (useActionState, useOptimistic, useFormStatus) for mutations and async form submissions. Prohibits manual useState submit wrappers, manual loading states, and synthetic event prevention (e.preventDefault()) that disrupt concurrent transitions and break native progressive enhancement. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Manual onSubmit State Orchestration with useState Pending/Error Flags and Imperative Rollbacks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftManual onSubmit State Orchestration with useState Pending/Error Flags and Imperative RollbacksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST use 'useActionState' instead of manual 'useState' bundles (isLoading, error, data) for executing mutations and async form actions.

Engineers MUST use 'useActionState' instead of manual 'useState' bundles (isLoading, error, data) for executing mutations and async form actions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Action handler functions passed to 'useActionState' MUST accept '(previousState, formData)' as standard parameters and return a predictable immutable state object.

Action handler functions passed to 'useActionState' MUST accept '(previousState, formData)' as standard parameters and return a predictable immutable state object.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT hijack form submission via 'onSubmit={handleSubmit}' with 'e.preventDefault()' when the operation is an async data mutation

Engineers MUST NOT hijack form submission via 'onSubmit={handleSubmit}' with 'e.preventDefault()' when the operation is an async data mutation; bind the action directly to '<form action={formAction}>' or submit buttons via 'formAction'.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST use 'useOptimistic' for rendering speculative UI changes

Engineers MUST use 'useOptimistic' for rendering speculative UI changes; manual setState mutations paired with imperative try/catch rollbacks are strictly forbidden.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components rendering submit buttons or pending indicators nested within forms MUST consume 'useFormStatus' rather than prop-drilling pending flags from parent components.

Components rendering submit buttons or pending indicators nested within forms MUST consume 'useFormStatus' rather than prop-drilling pending flags from parent components.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Engineers MUST ensure optimistic updates automatically revert upon rejected action promises by driving optimistic transitions through the action dispatcher returned by useActionState or startTransition.

Engineers MUST ensure optimistic updates automatically revert upon rejected action promises by driving optimistic transitions through the action dispatcher returned by useActionState or startTransition.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Server and client actions MUST throw or return serializable structured error payloads conforming to your application's domain error contracts.

Server and client actions MUST throw or return serializable structured error payloads conforming to your application's domain error contracts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is React 19 Actions: Mandating useActionState, useOptimistic, and useFormStatus over Manual State Wrappers critical for AI coding assistants?

Enforces native React 19 Action primitives (useActionState, useOptimistic, useFormStatus) for mutations and async form submissions. Prohibits manual useState submit wrappers, manual loading states, and synthetic event prevention (e.preventDefault()) that disrupt concurrent transitions and break native progressive enhancement. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Manual onSubmit State Orchestration with useState Pending/Error Flags and Imperative Rollbacks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

React