Cursor rule for React forms covering controlled vs uncontrolled inputs, React 19 useActionState and useFormStatus, server validation and double-submit safety.
.cursor/rules/react-form-handling.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for React forms covering controlled vs uncontrolled inputs, React 19 useActionState and useFormStatus, server validation and double-submit safety."
globs: "**/*"
alwaysApply: false
---
# React Form Handling
Applies to: React forms (sign-up, settings, checkout, search filters), including validation, submission state and error display.
Version baseline: checked against the React 19 docs (`<form action>`, `useActionState`, `useFormStatus`). Read the project's `react` version and its form library, if any (React Hook Form, TanStack Form, Conform, Formik). Follow the library's patterns when one is already in use. On React 18, form actions are not available; use `onSubmit` with `event.preventDefault()`.
## Controlled vs uncontrolled
- Use uncontrolled inputs (`name` + `defaultValue`, read via `FormData`) for simple submit-and-save forms. There is less state and less re-rendering.
- Use controlled inputs (`value` + `onChange`) when the UI must react to every keystroke: formatting as you type, dependent fields, live previews, enabling or disabling other fields.
- Never switch an input between controlled and uncontrolled. Keep `value` defined: use `""`, not `undefined`.
## Submitting with actions (React 19)
```tsx
import { useActionState, useId } from "react";
import { useFormStatus } from "react-dom";
type FormState = { errors: Partial<Record<"email" | "name", string>>; message: string };
async function saveProfile(_prev: FormState, formData: FormData): Promise<FormState> {
const email = String(formData.get("email") ?? "").trim();
const name = String(formData.get("name") ?? "").trim();
const errors: FormState["errors"] = {};
if (!/^[^\s@]+@[^\s@]+$/.test(email)) errors.email = "Enter a valid email address.";
if (!name) errors.name = "Name is required.";
if (Object.keys(errors).length) return { errors, message: "" };
await updateProfile({ email, name }); // project API call; the server validates again
return { errors: {}, message: "Profile saved." };
}
function SubmitButton() {
const { pending } = useFormStatus(); // must be rendered inside the <form>
return <button type="submit" disabled={pending}>{pending ? "Saving…" : "Save"}</button>;
}
export function ProfileForm() {
const [state, formAction] = useActionState(saveProfile, { errors: {}, message: "" });
const id = useId();
return (
<form action={formAction} noValidate>
<label htmlFor={`${id}-email`}>Email</label>
<input id={`${id}-email`} name="email" type="email" autoComplete="email" required
aria-invalid={state.errors.email ? true : undefined}
aria-describedby={state.errors.email ? `${id}-email-error` : undefined} />
{state.errors.email && <p id={`${id}-email-error`}>{state.errors.email}</p>}
<label htmlFor={`${id}-name`}>Name</label>
<input id={`${id}-name`} name="name" autoComplete="name" required
aria-invalid={state.errors.name ? true : undefined}
aria-describedby={state.errors.name ? `${id}-name-error` : undefined} />
{state.errors.name && <p id={`${id}-name-error`}>{state.errors.name}</p>}
<SubmitButton />
<p role="status">{state.message}</p>
</form>
);
}
```
- `useActionState` returns `[state, formAction, isPending]`. `useFormStatus` reads the pending state of the parent `<form>`, so call it in a child component.
- After a successful action, React resets uncontrolled fields of a `<form action>`. To keep the entered values when validation fails, return them in the state and pass them back as `defaultValue`.
## Validation
- Validate on the server (or in the API) every time. Client validation is a usability aid, not a security control.
- Share one schema between client and server when the stack allows it (for example Zod), so the messages match.
- Validate a field on blur or submit, not on every keystroke. Once a field has shown an error, re-validate it on change so the error clears as soon as it is fixed.
- Debounce only expensive or remote checks (username availability), typically 300–500 ms, and cancel stale requests (`AbortController`).
## Showing errors accessibly
- Show each error next to its field, linked with `aria-describedby`, and mark the field `aria-invalid`. Give every input a visible `<label>`.
- On a failed submit, move focus to the first invalid field or to an error summary at the top that links to the fields.
- Show a form-level error for failures not tied to a field (network, server 500) and keep the user's input.
## Loading and double submission
- Disable the submit button and show progress while pending. Also make the server operation idempotent (an idempotency key or unique constraint), because disabled buttons do not stop retries, double taps before re-render, or replayed requests.
- Use `useOptimistic` only when the UI can safely roll back.
## When to use a form library
Use the project's library, or propose one, for large forms with field arrays, multi-step wizards, cross-field rules or many async validators. Keep the accessibility and server-validation rules above either way.
## Verify before finishing
- Type-check, and test submitting valid data, each invalid field (the error text is linked via `aria-describedby`), a server failure (input preserved) and double-click (one request).
- Tab through the form with the keyboard, and confirm screen readers announce errors and the status message.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A developer asks Cursor to build or refactor a profile/settings form in a React 19 app so that it validates, shows accessible errors and cannot be submitted twice.
Rewrite ProfileForm.tsx. It keeps every field in useState, validates on every keystroke, shows errors in red text only, and users can double-click Save to send two PATCH requests. React 19.2, no form library; updateProfile() calls our API.
Illustrative; not a recorded model run. An uncontrolled form using <form action> with useActionState returning field errors and a status message, plus a SubmitButton child that uses useFormStatus to disable itself while pending. Each input has a visible label, aria-invalid and aria-describedby pointing to its error text, and a role="status" message. Validation runs on submit and again on the server. The answer notes the server should use an idempotency key, because disabling the button is not enough, and lists tests for invalid fields, server failure and double click.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/react-form-handling.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "React Form Handling: Actions, Validation, Accessible Errors and Double-Submit Safety project conventions"
globs: "**/*"
alwaysApply: false
---
# React Form Handling
Applies to: React forms (sign-up, settings, checkout, search filters), including validation, submission state and error display.
Version baseline: checked against the React 19 docs (`<form action>`, `useActionState`, `useFormStatus`). Read the project's `react` version and its form library, if any (React Hook Form, TanStack Form, Conform, Formik). Follow the library's patterns when one is already in use. On React 18, form actions are not available; use `onSubmit` with `event.preventDefault()`.
## Controlled vs uncontrolled
- Use uncontrolled inputs (`name` + `defaultValue`, read via `FormData`) for simple submit-and-save forms. There is less state and less re-rendering.
- Use controlled inputs (`value` + `onChange`) when the UI must react to every keystroke: formatting as you type, dependent fields, live previews, enabling or disabling other fields.
- Never switch an input between controlled and uncontrolled. Keep `value` defined: use `""`, not `undefined`.
## Submitting with actions (React 19)
```tsx
import { useActionState, useId } from "react";
import { useFormStatus } from "react-dom";
type FormState = { errors: Partial<Record<"email" | "name", string>>; message: string };
async function saveProfile(_prev: FormState, formData: FormData): Promise<FormState> {
const email = String(formData.get("email") ?? "").trim();
const name = String(formData.get("name") ?? "").trim();
const errors: FormState["errors"] = {};
if (!/^[^\s@]+@[^\s@]+$/.test(email)) errors.email = "Enter a valid email address.";
if (!name) errors.name = "Name is required.";
if (Object.keys(errors).length) return { errors, message: "" };
await updateProfile({ email, name }); // project API call; the server validates again
return { errors: {}, message: "Profile saved." };
}
function SubmitButton() {
const { pending } = useFormStatus(); // must be rendered inside the <form>
return <button type="submit" disabled={pending}>{pending ? "Saving…" : "Save"}</button>;
}
export function ProfileForm() {
const [state, formAction] = useActionState(saveProfile, { errors: {}, message: "" });
const id = useId();
return (
<form action={formAction} noValidate>
<label htmlFor={`${id}-email`}>Email</label>
<input id={`${id}-email`} name="email" type="email" autoComplete="email" required
aria-invalid={state.errors.email ? true : undefined}
aria-describedby={state.errors.email ? `${id}-email-error` : undefined} />
{state.errors.email && <p id={`${id}-email-error`}>{state.errors.email}</p>}
<label htmlFor={`${id}-name`}>Name</label>
<input id={`${id}-name`} name="name" autoComplete="name" required
aria-invalid={state.errors.name ? true : undefined}
aria-describedby={state.errors.name ? `${id}-name-error` : undefined} />
{state.errors.name && <p id={`${id}-name-error`}>{state.errors.name}</p>}
<SubmitButton />
<p role="status">{state.message}</p>
</form>
);
}
```
- `useActionState` returns `[state, formAction, isPending]`. `useFormStatus` reads the pending state of the parent `<form>`, so call it in a child component.
- After a successful action, React resets uncontrolled fields of a `<form action>`. To keep the entered values when validation fails, return them in the state and pass them back as `defaultValue`.
## Validation
- Validate on the server (or in the API) every time. Client validation is a usability aid, not a security control.
- Share one schema between client and server when the stack allows it (for example Zod), so the messages match.
- Validate a field on blur or submit, not on every keystroke. Once a field has shown an error, re-validate it on change so the error clears as soon as it is fixed.
- Debounce only expensive or remote checks (username availability), typically 300–500 ms, and cancel stale requests (`AbortController`).
## Showing errors accessibly
- Show each error next to its field, linked with `aria-describedby`, and mark the field `aria-invalid`. Give every input a visible `<label>`.
- On a failed submit, move focus to the first invalid field or to an error summary at the top that links to the fields.
- Show a form-level error for failures not tied to a field (network, server 500) and keep the user's input.
## Loading and double submission
- Disable the submit button and show progress while pending. Also make the server operation idempotent (an idempotency key or unique constraint), because disabled buttons do not stop retries, double taps before re-render, or replayed requests.
- Use `useOptimistic` only when the UI can safely roll back.
## When to use a form library
Use the project's library, or propose one, for large forms with field arrays, multi-step wizards, cross-field rules or many async validators. Keep the accessibility and server-validation rules above either way.
## Verify before finishing
- Type-check, and test submitting valid data, each invalid field (the error text is linked via `aria-describedby`), a server failure (input preserved) and double-click (one request).
- Tab through the form with the keyboard, and confirm screen readers announce errors and the status message.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.