Skip to content

Default Options

As you create more forms, you start to handle them the same way each time. For example, we may have an invalid submission handler that isn't tied to any particular form:

ts
const form = useForm({
  defaultValues: { firstName: '' },
  validators: [/* ... */],
  onSubmitInvalid: ({ reason, preventThrow }) => {
    preventThrow()
    if (reason === 'validation') {
      // Focus on the first invalid input element
      document.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
    }
  },
})

We can create a custom function and pass it to every form hook, but we still have to remember to do so.

Default options

That's where form composition comes in: it reduces UI boilerplate and, in our case, lets us set default options.

Let's use the function above as a default:

ts
import { createFormHook } from '@tanstack/react-form'

export const { useAppForm, appFormOptions, defineAppFieldGroup } =
  createFormHook({
    fieldComponents: {/* See guide for Field components */},
    formComponents: {/* See guide for Form components */},
    defaultOptions: {
      // Default options for useForm
      forms: {
        onSubmitInvalid: ({ reason, preventThrow }) => {
          preventThrow()
          if (reason === 'validation') {
            document
              .querySelector<HTMLElement>('[aria-invalid="true"]')
              ?.focus()
          }
        },
      },
      // Default options for <form.FormGroup />
      formGroups: {
        onSubmitInvalid: ({ reason, preventThrow }) => {
          preventThrow()
          if (reason === 'validation') {
            document
              .querySelector<HTMLElement>('[aria-invalid="true"]')
              ?.focus()
          }
        },
      },
    },
  })

The form hook supports UI components, but for now, we'll focus on the three functions it returns. These replace the following:

NormalForm hook variant
useFormuseAppForm
formOptionsappFormOptions
defineFieldGroupdefineAppFieldGroup

In a component, we can now use the form hook:

ts
const form = useAppForm({
  defaultValues: { firstName: '' },
  validators: [/* ... */],
  // Invalid submissions are handled automatically now
})

Overriding options

If a particular form needs to handle invalid submissions differently, you can define its handler in useAppForm:

ts
const form = useAppForm({
  defaultValues: { firstName: '' },
  validators: [/* ... */],
  onSubmitInvalid: ({ preventThrow }) => {
    preventThrow()
    // This form is on a page that uses toast messages
    toast('Could not submit!')
  },
})

If you need to opt out of the default altogether, you can also provide undefined:

ts
const form = useAppForm({
  defaultValues: { firstName: '' },
  validators: [/* ... */],
  // Do not apply the default option
  onSubmitInvalid: undefined,
})

Merging options

Sometimes, you may want to keep the default option when adding a local option. For example, consider a default listener that logs data:

ts
import { createFormHook } from '@tanstack/react-form'

const { useAppForm } = createFormHook({
  fieldComponents: {},
  formComponents: {},
  defaultOptions: {
    forms: {
      listeners: [
        {
          run: ({ value }) => {
            console.log('Value changed:', value)
          },
          triggers: ['change'],
          triggerDebounceMs: 500,
        },
      ],
    },
  },
})

However, with this setup, adding local form listeners would replace the default listener:

ts
const form = useAppForm({
  defaultValues: { firstName: '' },
  listeners: [
    {
      triggers: ['change'],
      run: () => {
        console.log('Oops! The default logger was lost.')
      },
    },
  ],
})

To control how local options combine with defaults, you can choose from three behaviors:

  • 'replaceDefault' - This is the default behavior when you pass a value directly. Any local option replaces the default.
  • 'localFirst' - For functions like onSubmitInvalid, the local function runs before the default function. For arrays like listeners, the local listeners come first.
  • 'defaultFirst' - The opposite of 'localFirst'. Local options are placed or executed after the defaults.

Let's configure the default logging listener to come before local listeners:

ts
import { createFormHook } from '@tanstack/react-form'

const { useAppForm } = createFormHook({
  fieldComponents: {},
  formComponents: {},
  defaultOptions: {
    forms: {
      // Use an object with `value` and `behaviour` instead of passing the array directly
      listeners: {
        // The listener code can stay as-is.
        value: [
          {
            run: ({ value }) => {
              console.log('Value changed:', value)
            },
            triggers: ['change'],
            triggerDebounceMs: 500,
          },
        ],
        // If local listeners are used, the form will use
        // [...defaultListeners, ...localListeners]
        behaviour: 'defaultFirst',
      },
    },
  },
})