Loading...
Loading...
TanStack Form best practices for type-safe form management, validation, field composition, and submission handling in React. Use when building forms with complex validation, integrating schema libraries (Zod/Valibot/ArkType), composing reusable form components, managing array/dynamic fields, or integrating with meta-frameworks (TanStack Start, Next.js, Remix).
npx skill4agent add fellipeutaka/leon tanstack-formnpm install @tanstack/react-formimport { useForm } from '@tanstack/react-form'
function App() {
const form = useForm({
defaultValues: {
firstName: '',
lastName: '',
},
onSubmit: async ({ value }) => {
console.log(value)
},
})
return (
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
>
<form.Field
name="firstName"
validators={{
onChange: ({ value }) =>
!value ? 'Required' : value.length < 3 ? 'Too short' : undefined,
}}
children={(field) => (
<>
<input
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
{!field.state.meta.isValid && (
<em>{field.state.meta.errors.join(', ')}</em>
)}
</>
)}
/>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
children={([canSubmit, isSubmitting]) => (
<button type="submit" disabled={!canSubmit}>
{isSubmitting ? '...' : 'Submit'}
</button>
)}
/>
</form>
)
}createFormHookimport { createFormHookContexts, createFormHook } from '@tanstack/react-form'
import { TextField, NumberField, SubmitButton } from '~/ui-library'
const { fieldContext, formContext } = createFormHookContexts()
export const { useAppForm } = createFormHook({
fieldComponents: { TextField, NumberField },
formComponents: { SubmitButton },
fieldContext,
formContext,
})npm install -D @tanstack/react-devtools @tanstack/react-form-devtoolsimport { TanStackDevtools } from '@tanstack/react-devtools'
import { formDevtoolsPlugin } from '@tanstack/react-form-devtools'
<TanStackDevtools
config={{ hideUntilHover: true }}
plugins={[formDevtoolsPlugin()]}
/>| Priority | Category | Rule File | Impact |
|---|---|---|---|
| CRITICAL | Form Setup | | Correct form creation and type inference |
| CRITICAL | Validation | | Prevents invalid submissions and poor UX |
| CRITICAL | Schema Validation | | Type-safe validation with Zod/Valibot/ArkType |
| HIGH | Form Composition | | Reduces boilerplate, enables reusable components |
| HIGH | Field State | | Correct state access and reactivity |
| HIGH | Array Fields | | Dynamic list management |
| HIGH | Linked Fields | | Cross-field validation (e.g. confirm password) |
| MEDIUM | Listeners | | Side effects on field events |
| MEDIUM | Submission | | Correct submit handling and meta passing |
| MEDIUM | SSR / Meta-Frameworks | | Server validation with Start/Next.js/Remix |
| LOW | UI Libraries | | Headless integration with component libraries |
useForm<T>()defaultValuese.preventDefault(); e.stopPropagation(); form.handleSubmit()childrenform.Fieldchildren={(field) => ...}form.SubscribeuseStoreuseStore(form.store, (s) => s.values.name)useStore(form.store)createFormHookonChangeAsyncDebounceMsasyncDebounceMsuseForm<MyType>()defaultValuese.preventDefault()useFielduseStore(form.store)form.SubscribeuseStoretype="reset"e.preventDefault()form.reset()onSubmitonSubmit// Schema validation (form-level with Zod)
const form = useForm({
defaultValues: { age: 0, name: '' },
validators: {
onChange: z.object({ age: z.number().min(13), name: z.string().min(1) }),
},
onSubmit: ({ value }) => console.log(value),
})
// Array fields
<form.Field name="hobbies" mode="array" children={(field) => (
<div>
{field.state.value.map((_, i) => (
<form.Field key={i} name={`hobbies[${i}].name`} children={(sub) => (
<input value={sub.state.value} onChange={(e) => sub.handleChange(e.target.value)} />
)} />
))}
<button type="button" onClick={() => field.pushValue({ name: '' })}>Add</button>
</div>
)} />
// Linked fields (confirm password)
<form.Field name="confirm_password" validators={{
onChangeListenTo: ['password'],
onChange: ({ value, fieldApi }) =>
value !== fieldApi.form.getFieldValue('password') ? 'Passwords do not match' : undefined,
}} children={(field) => <input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />} />
// Listeners (reset province when country changes)
<form.Field name="country" listeners={{
onChange: ({ value }) => { form.setFieldValue('province', '') },
}} children={(field) => <input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />} />
// Form composition with withForm
const ChildForm = withForm({
defaultValues: { firstName: '', lastName: '' },
render: function Render({ form }) {
return <form.AppField name="firstName" children={(field) => <field.TextField label="First Name" />} />
},
})