typescriptbeginner

useFormStatus for Pending UI States

Use useFormStatus hook to show loading states during server action form submissions.

typescript
'use client';

import { useFormStatus } from 'react-dom';

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button
      type="submit"
      disabled={pending}
      className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
    >
      {pending ? (
        <span className="flex items-center gap-2">
          <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
          </svg>
          Submitting...
        </span>
      ) : (
        'Submit'
      )}
    </button>
  );
}

// Server action
async function createItem(formData: FormData) {
  'use server';
  await new Promise((r) => setTimeout(r, 2000)); // simulate delay
  const name = formData.get('name');
  // Save to database...
}

export default function ItemForm() {
  return (
    <form action={createItem}>
      <input name="name" required className="border p-2 rounded" />
      <SubmitButton />
    </form>
  );
}

Use Cases

  • form submission UX
  • loading indicators
  • server action forms

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.