FormIntermediateSSR-safehooks/forms/useFormSubmit.ts

useFormSubmit

Async submit flag helper.

Import

TypeScript
import { useFormSubmit } from '@/hooks';

API

Signature

useFormSubmit({ onSubmit, validate? })

When to use

Use useFormSubmit instead of re-implementing the same pattern in multiple components.

SSR / Next.js

SSR-safe state machines.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useFormSubmit
Editor
function Submit() {
  const { submit, isSubmitting, submitError } = useFormSubmit<{ name: string }>({
    onSubmit: async (v) => {
      await fetch('/api', { method: 'POST', body: JSON.stringify(v) });
    },
  });
  return (
    <button disabled={isSubmitting} onClick={() => void submit({ name: 'Ada' })}>
      {submitError?.message ?? (isSubmitting ? '…' : 'Submit')}
    </button>
  );
}
Preview

Implementation source

Full library source for useFormSubmit — copy into your project when you are not installing a package yet.

hooks/forms/useFormSubmit.ts
import { useCallback, useState } from 'react';

export interface UseFormSubmitOptions<T> {
  onSubmit: (values: T) => void | Promise<void>;
  validate?: (values: T) => boolean | Promise<boolean>;
}

/** Submit helper with async support and submitting flag. */
export function useFormSubmit<T>(options: UseFormSubmitOptions<T>) {
  const { onSubmit, validate } = options;
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<Error | null>(null);
  const [submitCount, setSubmitCount] = useState(0);

  const submit = useCallback(
    async (values: T) => {
      setSubmitError(null);
      if (validate) {
        const ok = await validate(values);
        if (!ok) return false;
      }
      setIsSubmitting(true);
      setSubmitCount((c) => c + 1);
      try {
        await onSubmit(values);
        return true;
      } catch (e) {
        setSubmitError(e instanceof Error ? e : new Error(String(e)));
        return false;
      } finally {
        setIsSubmitting(false);
      }
    },
    [onSubmit, validate],
  );

  return { submit, isSubmitting, submitError, submitCount };
}

Copy-paste example

useFormSubmit.example.tsx
'use client';

import { useFormSubmit } from '@/hooks';

export function Submit() {
  const { submit, isSubmitting, submitError } = useFormSubmit<{ name: string }>({
    onSubmit: async (v) => {
      await fetch('/api', { method: 'POST', body: JSON.stringify(v) });
    },
  });
  return (
    <button disabled={isSubmitting} onClick={() => void submit({ name: 'Ada' })}>
      {submitError?.message ?? (isSubmitting ? '…' : 'Submit')}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Field name attributes must match keys in initialValues for handleChange.
  • Source of truth: open hooks/forms/useFormSubmit.ts for implementation details