TanStackT
TanStack6mo ago
5 replies
popular-magenta

Question about TanStack Form `formOptions` vs regular object

Hey everyone! 👋

I'm trying to understand the practical difference between using formOptions() vs just exporting a regular object with the same structure in TanStack Form.

Using formOptions():
interface User {
  firstName: string
  lastName: string
  hobbies: Array<string>
}
const defaultUser: User = { firstName: '', lastName: '', hobbies: [] }

const formOpts = formOptions({
  defaultValues: defaultUser,
  // other options...
})

const form = useForm({
  ...formOpts,
  onSubmit: async ({ value }) => {
    console.log(value)
  },
})


vs regular object:
interface User {
  firstName: string
  lastName: string
  hobbies: Array<string>
}
const defaultUser: User = { firstName: '', lastName: '', hobbies: [] }

const formOpts = {
  defaultValues: defaultUser,
  // other options...
}

const form = useForm({
  ...formOpts,
  onSubmit: async ({ value }) => {
    console.log(value)
  },
})


What are the actual benefits/differences of using the formOptions() function? Is it just for type safety, or does it provide additional functionality under the hood?

My original thought was that it would allow you to add defaultValues, validators, etc all in one place—and then export that use it across your app (using form composition).

But then I saw this form-questionsAre validators not supposed to be defined inside of formOptions? thread, and this GitHub Issue —so I’m slightly confused. I also think it might be helpful if the docs explained why you would go one route over the other (as it shows using formOptions and a regular object).

I'm also curious about when using formOptions with withForm - especially when the form options include validators. Does formOptions() provide better type inference or validation handling when passed to withForm compared to a regular object with the same validator functions?

Reference: TanStack Form Docs - Form Options

Thank you! 🙏
Was this page helpful?