Skip to content
Mosaic
On this page

useForm

Owns a form's values, validation, submit and errors in a machine. Field errors show once a field is touched; submit touches every field, waits for pending async checks and focuses the first invalid control.

Use for

  • a form: values, validation, submit, field errors, success UI
  • a server check on a field as the user types, with validateAsync
  • Clerk errors from a save landing on form fields

Practices

GuidancePractice
DoReject onSubmit with FormSubmitError (exported from this unit), or use save in the model, so errors land on fields and the banner.
DoUse onSuccess for success UI that stays mounted, such as a done step.
DoSpread register(name) on an onChange control and registerValue(name) on an onValueChange one.
DoPass form whole to the view.
Don’tWrap onSubmit in try/catch. Reject, and the form shows why.
Don’tTrack a submitting flag in useState. Read isSubmitting.

Options

PropTypeDescription
initialValuesTValuesThe starting values, and the baseline isDirty compares against until reset(values).
fieldsFieldsConfig<TValues>Per-field validate and validateAsync, each returning feedback or undefined.
onSubmit(values: TValues) => Promise<TResult>Runs with the values when the form is valid. Reject to show the error.
onSuccess(result: TResult, submittedValues: TValues) => voidCalled with the result and the submitted values after onSubmit resolves.
canSubmit(values: TValues) => booleanAn extra check on the values before submit is allowed.Default: always true
errorFallbackstringCopy shown when the submit fails without an error the form can describe.Default: the generic form error

Returns

PropTypeDescription
idstringA stable id. Pass it to the Form and to a SubmitButton form outside it.
valuesTValuesThe current values.
fieldsRecord<keyof TValues, FormField>Per field: feedback, isValidating, touched and isDirty.
errorstringForm-level copy for the last failed submit, for Card.Banner.
isSubmittingbooleanWhether a submit is queued behind async checks or running.
isDirtybooleanWhether any value differs from its initial value.
canSubmitbooleanWhether every field is valid and canSubmit passes.
register<K extends TextFieldName<TValues>>(name: K) => RegisteredField<TValues, K>Props for a string field on a control that takes onChange(event).
registerValue<K extends keyof TValues>(name: K) => RegisteredValueField<TValues, K>Props for a field of any type on a control that takes onValueChange(value).
setValue<K extends keyof TValues>(name: K, value: TValues[K]) => voidSets one value, clearing its submit error and starting its async check.
touch(name: keyof TValues) => voidMarks a field touched, so its error shows.
submit() => voidSubmits, or focuses the first invalid control.
handleSubmit(event: { preventDefault: () => void }) => voidA <form> submit handler: prevents the default, then submits.
reset(values?: TValues) => voidClears touched state and errors and resets to the initial values, or to values, which become the new baseline.

Examples

A form in a view

TSX
<Form id={form.id} onSubmit={form.handleSubmit}>
  <Card.Banner color='negative'>{form.error}</Card.Banner>
  <Field.Root invalid={form.fields.email.feedback?.type === 'error'}>
    <Field.Label>{m.email}</Field.Label>
    <Input {...form.register('email')} />
    <Field.Feedback feedback={form.fields.email.feedback} />
  </Field.Root>
  <SubmitButton isPending={form.isSubmitting} disabled={!form.canSubmit}>
    {m.save}
  </SubmitButton>
</Form>