Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

migrate-from-v1.md

1,088 lines35.7 KB

1---
2id: migrate-from-v1
3title: Migrating from v1
4---
5​
6TanStack Form v2 keeps the same core idea as v1: create a form with
7`useForm`, render fields from the returned form API, and submit with
8`form.handleSubmit()`. Most migrations are not a full rewrite, but v2 does
9change several React-facing APIs that show up in examples and integration
10tests.
11​
12This page is a starting checklist for migrating React apps from v1 to v2.
13​
14## Quick checklist
15​
16- Keep `useForm`, `defaultValues`, `onSubmit`, `form.Field`, and
17 `form.Subscribe`, but update render props from `field.state.value` and
18 `field.state.meta` to `field.value` and `field.meta`.
19- Always provide `defaultValues` to `useForm`. v2 does not support omitting
20 them.
21- Move field-level `defaultValue` props into form-level `defaultValues`.
22- Remove field-level `defaultMeta` props. Model initial validation and error
23 visibility through validators, `runOnMount`, and `errorVisibility`.
24- Change validation from keyed event objects like `{ onChange, onBlur }` to
25 arrays of validator objects with `run` and `triggers`.
26- Change async validator debounce options such as `onChangeAsyncDebounceMs` to
27 `triggerDebounceMs` on the validator object.
28- Change field cross-validation from `onChangeListenTo` / `onBlurListenTo` to
29 `watchFields` on validators or listeners.
30- Replace `mode="array"` fields with `form.ArrayField`.
31- Keep array mutations on the `ArrayField` render prop, such as
32 `array.pushValue(...)`, or use path-based form methods such as
33 `form.pushFieldValue(...)` when the control lives outside the render prop.
34- Rename `form.moveFieldValues` to `form.moveFieldValue`, and replace removed
35 form methods such as `setFieldMeta` and `validateField` as described in
36 [Removed and renamed form methods](#removed-and-renamed-form-methods).
37- Read errors from `field.errors`, `group.state.errors`, and
38 `form.state.errors` as validation issue objects. Use `error.message` when
39 rendering text.
40- In form- and group-level validators, build routed errors with
41 `createErrorMap(...)` and return the map directly.
42- Return `createValidationError(...)` from `onSubmit` when a submit handler
43 needs to route server errors back to form or field state.
44- Use `useSelector`, which replaces v1's deprecated `useStore` usage.
45- Subscribe to `form.atom` and `field.atom` instead of `form.store` and
46 `field.store`.
47- Use `formOptions(...)` for shared base form options.
48- Replace `withForm` components with plain components that accept a `form` prop
49 typed as `ReactFormType<typeof formOpts>`.
50- Replace `useFormGroup` with `form.FormGroup` for scoped sections of the same
51 form.
52- Replace `withFieldGroup` with `defineFieldGroup(...).bindComponent(...)` for
53 reusable field bundles that map virtual field names to different concrete
54 form paths.
55- Upgrade Vue to version 3.6 or newer when using the Vue adapter. Form
56 Composition relies on behavior introduced in Vue 3.6.
57- Update CommonJS integrations to consume ESM. The v2 packages do not publish
58 a CommonJS build and require Node.js 18 or newer.
59- Upgrade React to version 18 or newer. The v2 React adapter no longer supports
60 React 17.
61- Update CommonJS integrations to consume ESM. The v2 packages do not publish
62 a CommonJS build and require Node.js 18 or newer.
63​
64## React version
65​
66The v2 React adapter supports React 18 and 19. React 17 is no longer supported,
67so upgrade `react`, `react-dom`, and their corresponding type packages before
68migrating. If you imported `CrossVersionReactNode` from `@tanstack/react-form`,
69import `ReactNode` from `react` instead.
70​
71## Vue version
72​
73The v2 Vue adapter requires Vue 3.6 or newer. At the time of writing, Vue 3.6
74has not yet been released as stable and is available as a release candidate.
75We hope Vue 3.6 will be stable by the time TanStack Form v2 becomes stable.
76​
77Form Composition relies on Vue 3.6 behavior to work correctly. Requiring it
78from the start lets the Vue adapter support Form Composition without adding a
79breaking minimum-version change later in the v2 release line.
80​
81## Package format
82​
83The v2 core, framework, devtools, and server-adapter packages publish ESM
84exports only and declare Node.js 18 as their minimum version. Prefer `import` /
85`export` syntax, use dynamic `import()` when consuming them from CommonJS, and
86make sure any Node-based test, SSR, or build tooling can load ESM dependencies.
87There is no separate CommonJS build or `require` export to fall back to.
88​
89## Basic fields
90​
91The v1 simple example and v2 basic example are intentionally similar. The main
92render-prop difference is that v2 exposes the subscribed field surface directly.
93​
94```tsx
95// v1
96<form.Field name="firstName">
97 {(field) => (
98 <input
99 name={field.name}
100 value={field.state.value}
101 onBlur={field.handleBlur}
102 onChange={(event) => field.handleChange(event.target.value)}
103 />
104 )}
105</form.Field>
106```
107​
108```tsx
109// v2
110<form.Field name="firstName">
111 {(field) => (
112 <input
113 name={field.name}
114 value={field.value}
115 onBlur={field.handleBlur}
116 onChange={(event) => field.handleChange(event.target.value)}
117 aria-invalid={field.meta.isInvalid}
118 />
119 )}
120</form.Field>
121```
122​
123The same applies to common meta and error reads:
124​
125```tsx
126// v1
127field.state.value
128field.state.meta.isTouched
129field.state.meta.isValid
130field.state.meta.errors.join(',')
131```
132​
133```tsx
134// v2
135field.value
136field.meta.isTouched
137field.meta.isValid
138field.errors.map((error) => error.message).join(',')
139```
140​
141v2 also exposes `field.meta.isInvalid`, which is the inverse of `isValid` and
142is convenient for attributes such as `aria-invalid`.
143​
144The v2 React integration tests also assert that fields rerender independently
145when sibling fields change. Prefer reading only the subscribed field values and
146meta you need in each render prop.
147​
148## Defaults and initial meta
149​
150In v1, a form could rely on field-level `defaultValue` props:
151​
152```tsx
153// v1
154const form = useForm({
155 defaultValues: {} as Person,
156})
157​
158<form.Field name="firstName" defaultValue="">
159 {(field) => <input value={field.state.value} />}
160</form.Field>
161```
162​
163In v2, `defaultValues` are required on the form and are the only place to define
164initial values:
165​
166```tsx
167// v2
168const form = useForm({
169 defaultValues: {
170 firstName: '',
171 lastName: '',
172 },
173})
174​
175<form.Field name="firstName">
176 {(field) => <input value={field.value} />}
177</form.Field>
178```
179​
180`<form.Field defaultMeta={...}>` was also removed. If v1 code used
181`defaultMeta={{ isTouched: true }}` to show errors immediately, replace the
182implicit meta state with mount validation and an explicit visibility policy:
183​
184```tsx
185// v2
186const form = useForm({
187 defaultValues: {
188 firstName: '',
189 },
190})
191​
192<form.Field
193 name="firstName"
194 validators={[
195 {
196 runOnMount: true,
197 triggers: ['change', 'blur'],
198 run: ({ value }) => (value ? undefined : 'First name is required'),
199 },
200 ]}
202 {(field) => (
203 <>
204 <input
205 value={field.value}
206 onBlur={field.handleBlur}
207 onChange={(event) => field.handleChange(event.target.value)}
208 />
209 {field.errors.map((error) => (
210 <p key={error.message}>{error.message}</p>
211 ))}
212 </>
213 )}
214</form.Field>
215```
216​
217If errors should validate on mount but remain hidden until the user blurs the
218field or tries to submit, use a form-level policy such as
219`errorVisibility: ({ fieldState, state }) => fieldState.meta.isBlurred ||
220state.submissionAttempts > 0` instead.
221​
222## Validators
223​
224v1 validators are keyed by event names:
225​
226```tsx
227// v1
228<form.Field
229 name="firstName"
230 validators={{
231 onChange: ({ value }) =>
232 !value
233 ? 'A first name is required'
234 : value.length < 3
235 ? 'First name must be at least 3 characters'
236 : undefined,
237 onChangeAsyncDebounceMs: 500,
238 onChangeAsync: async ({ value }) => {
239 await checkName(value)
240 return value.includes('error')
241 ? 'No "error" allowed in first name'
242 : undefined
243 },
244 }}
245/>
246```
247​
248v2 validators are ordered arrays. Each validator has a `run` function or
249standard schema, a `triggers` list, and optional behavior like debouncing or
250bailing:
251​
252```tsx
253// v2
254<form.Field
255 name="firstName"
256 validators={[
257 {
258 run: ({ value }) => {
259 if (value.length === 0) return 'A first name is required'
260 if (value.length < 3) return 'First name is too short'
261 },
262 triggers: ['change', 'blur'],
263 triggerDebounceMs: 300,
264 },
265 {
266 run: async ({ value }) => {
267 await checkName(value)
268 return value.toLowerCase().includes('error')
269 ? 'No "error" allowed in first name'
270 : undefined
271 },
272 triggers: ['change'],
273 bailIfInvalid: true,
274 },
275 ]}
276/>
277```
278​
279Useful translations:
280​
281| v1 | v2 |
282| ------------------------------------- | --------------------------------------------------------------------------------- |
283| `validators.onMount` | validator with `runOnMount: true` |
284| `validators.onChange` | validator with `triggers: ['change']` |
285| `validators.onBlur` | validator with `triggers: ['blur']` |
286| `validators.onSubmit` | validator with `triggers: []`, or rely on submit running validators by default |
287| `onChangeAsync` | async `run` with `triggers: ['change']` |
288| `onChangeAsyncDebounceMs` | `triggerDebounceMs` |
289| `onChangeListenTo` / `onBlurListenTo` | `watchFields` |
290| `validationLogic: revalidateLogic()` | migrate to explicit `triggers`, `when`, `skipOnSubmit`, and `bailIfInvalid` rules |
291​
292Submission is separate from the `triggers` list: every validator runs during
293submission by default. An empty `triggers: []` therefore means "no change or
294blur validation, but still validate on submit." Set `skipOnSubmit: true` when a
295validator must not run during client submission; do not add `'submit'` to
296`triggers`.
297​
298`triggers` can contain strings or trigger config objects. Use config objects
299when a validator should only run for some changes:
300​
301```tsx
302validators={[
303 {
304 triggers: [
305 {
306 trigger: 'change',
307 when: ({ value }) => Boolean(value),
308 },
309 ],
310 watchFields: ['startDate'],
311 run: ({ value, formApi }) => {
312 const startDate = formApi.getFieldValue('startDate')
313 if (value < startDate) return 'End date must be after the start date'
314 },
315 },
316]}
317```
318​
319Predicate callbacks are scope-aware. A `when` callback, a function-valued
320`skipOnSubmit`, or a function-valued `triggerDebounceMs` receives `scope` and
321`formApi`; field predicates receive the field being validated as `fieldApi`,
322while group predicates also receive `groupApi`. For form and group predicates,
323an optional `fieldApi` is the field that triggered validation.
324​
325Use `createValidator(...)` when the scheduling policy should be reused with
326different validator functions or schemas while preserving their inferred
327types:
328​
329```tsx
330import { createValidator } from '@tanstack/react-form'
331​
332const validateAfterSubmit = createValidator({
333 triggers: [
334 {
335 trigger: 'change',
336 when: ({ groupApi, formApi }) =>
337 (groupApi?.state.submissionAttempts ??
338 formApi.state.submissionAttempts) > 0,
339 },
340 ],
341})
342​
343const validators = [validateAfterSubmit(schema)]
344```
345​
346## Standard schemas
347​
348v1 accepted standard schemas in event-keyed validators:
349​
350```tsx
351// v1
352useForm({
353 defaultValues,
354 validators: {
355 onChange: schema,
356 },
357})
358```
359​
360In v2, pass schemas as `run` values inside the validators array:
361​
362```tsx
363// v2
364useForm({
365 defaultValues,
366 validators: [
367 {
368 run: schema,
369 triggers: ['change'],
370 },
371 ],
372})
373```
374​
375The form's `value` remains its editable input state. When a Standard Schema
376validator runs successfully during submission, its parsed output is available
377in `onSubmit` at the corresponding `schemaOutputs` index. Non-schema entries
378are `undefined`. Validators with literal `skipOnSubmit: true` are skipped during
379submission, and their slots are typed as `undefined`. Use the parsed entry when
380an endpoint expects the schema's output type.
381​
382For schema-led option inference, pass the schema first and the options second.
383`formOptions.strictSchema(...)` uses the schema input as the form shape, while
384`formOptions.looseSchema(...)` permits editable nullish defaults and combines
385them with the schema shape. These option helpers only affect types; the
386validators still perform the runtime parsing.
387​
388When manually calling a schema, return `parseIssues(...)` with the failed issue
389array. In a field validator it produces field issues; in a form or group
390validator it routes issue paths into a form/field map; and in `onSubmit` it
391produces a branded submit validation result. The v2 field-group example uses
392this helper after calling `schema.safeParse(...)`.
393​
394## Errors and submit results
395​
396v1 examples commonly render errors from `field.state.meta.errors`. In v2,
397render from `field.errors` for fields, `group.state.errors` for form groups, and
398`form.state.errors` for the form. Each of the group and form collections is an
399array. The items are validation issue objects, so render `error.message`.
400​
401```tsx
402function FieldError({ field }: { field: AnyFieldApi }) {
403 return (
404 <small role={field.meta.isInvalid ? 'alert' : undefined} aria-live="polite">
405 {field.errors.map((error) => error.message).join('\n')}
406 </small>
407 )
409```
410​
411Form- and group-level validators can route errors to the form and individual
412fields. Build a map with the `createErrorMap` supplied to `run`, then return the
413map itself:
414​
415```tsx
416const form = useForm({
417 defaultValues: {
418 firstName: '',
419 },
420 validators: [
421 {
422 triggers: ['change'],
423 run: ({ value, createErrorMap }) => {
424 const errors = createErrorMap()
425​
426 if (!value.firstName.trim()) {
427 errors.form = 'Please correct the highlighted fields'
428 errors.fields.firstName = 'First name is required'
429 }
430​
431 return errors
432 },
433 },
434 ],
435})
436```
437​
438`createErrorMap` also accepts an initial `{ form, fields }` object. An empty
439returned map is treated as a valid result.
440Field-level validators continue to return their own issue, string, issue array,
441or a valid result directly.
442​
443Submit handlers can now return a typed validation result. Use
444`createValidationError` to route endpoint errors back into form state:
445​
446```tsx
447const form = useForm({
448 defaultValues: {
449 firstName: '',
450 lastName: '',
451 },
452 onSubmit: async ({ value, createValidationError }) => {
453 const result = await saveUser(value)
454​
455 if (!result.ok) {
456 return createValidationError({
457 form: 'Could not save user',
458 fields: {
459 firstName: 'Name already exists',
460 lastName: 'Name already exists',
461 },
462 })
463 }
464​
465 return null
466 },
467})
468```
469​
470`form.handleSubmit()` resolves to the validation-result array for that
471submission attempt, so framework examples can await it and continue to native
472or server submission when `errors.length === 0`. A thrown or rejected
473`onSubmit` marks submission unsuccessful but is not added to that array. Return
474`createValidationError(...)` or `parseIssues(...)` when a submit failure should
475become validation state.
476​
477## Selectors and atoms
478​
479v1 re-exported `useStore` from `@tanstack/react-store`, but that usage was
480deprecated before v2. In v2, use `useSelector` and subscribe to atoms:
481​
482```tsx
483// v1
484import { useStore } from '@tanstack/react-store'
485​
486const errors = useStore(form.store, (state) => state.errors)
487const fieldErrors = useStore(field.store, (state) => state.meta.errors)
488```
489​
490```tsx
491// v2
492import { useSelector } from '@tanstack/react-form'
493​
494const errors = useSelector(form.atom, (state) => state.errors)
495const fieldErrors = useSelector(field.atom, (state) => state.meta.errors)
496```
497​
498The same rename applies when subscribing to field groups:
499​
500```tsx
501const values = useSelector(fields.atom, (values) => values)
502```
503​
504Reading `form.state` or `group.state` gives an imperative snapshot; it does not
505subscribe a React component. Use field render props, `form.Subscribe`,
506`group.Subscribe`, or `useSelector` for reactive reads, and keep selectors
507focused on the state the component renders.
508​
509## Arrays
510​
511v1 represented array fields with `mode="array"` and exposed array helpers from
512the field render prop:
513​
514```tsx
515// v1
516<form.Field name="people" mode="array">
517 {(field) => (
518 <>
519 {field.state.value.map((_, index) => (
520 <form.Field key={index} name={`people[${index}].name`}>
521 {(subField) => (
522 <input
523 value={subField.state.value}
524 onChange={(event) => subField.handleChange(event.target.value)}
525 />
526 )}
527 </form.Field>
528 ))}
529 <button
530 type="button"
531 onClick={() => field.pushValue({ name: '', age: 0 })}
532 >
533 Add person
534 </button>
535 </>
536 )}
537</form.Field>
538```
539​
540v2 uses a dedicated `form.ArrayField` component for array subscriptions. Its
541render prop still exposes array methods, so the direct migration can keep the
542mutation next to the rendered array:
543​
544```tsx
545// v2
546<form.ArrayField name="people">
547 {(array) => (
548 <>
549 {array.value.map((_, index) => (
550 <form.Field key={index} name={`people[${index}].name`}>
551 {(field) => (
552 <input
553 name={field.name}
554 value={field.value}
555 onBlur={field.handleBlur}
556 onChange={(event) => field.handleChange(event.target.value)}
557 />
558 )}
559 </form.Field>
560 ))}
561 <button
562 type="button"
563 onClick={() => array.pushValue({ name: '', age: 0 })}
564 >
565 Add person
566 </button>
567 </>
568 )}
569</form.ArrayField>
570```
571​
572When the mutation control is outside `ArrayField`, use the path-based form API
573instead:
574​
575```tsx
576form.pushFieldValue('people', { name: '', age: 0 })
577```
578​
579The same choice is available for inserting, removing, moving, swapping,
580filtering, and clearing values: use the relative methods on `array` or the
581field-path methods on `form`.
582​
583The v2 array example calls out the performance reason for this change:
584`ArrayField` lets the array shell rerender when the array structure changes
585without forcing the whole list to rerender for every item value change.
586​
587For current usage and adapter-specific examples, see [Arrays](./arrays).
588​
589## Removed and renamed form methods
590​
591The v2 form API is smaller than v1's. It reads and updates values, mutates
592arrays, runs form-level validation, submits, and resets. Field metadata now
593lives on the field API, validators and submit results produce errors instead
594of code writing them directly, and nothing replaces the internal
595field-registry helpers.
596​
597| v1 | v2 |
598| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
599| `moveFieldValues(name, from, to)` | `moveFieldValue(name, from, to)` |
600| `setFieldMeta(name, updater)` | `setFieldValue` update options, `handleSubmit()`, or `errorVisibility` |
601| `getFieldMeta(name)` | `field.meta` |
602| `resetFieldMeta(...)` | `resetField(name)`, `field.reset()`, or `reset(form.state.values, { updateDefaultValues: false })` |
603| `validateField(name, cause)` | validator `triggers` and `watchFields` |
604| `validateAllFields(cause)` | `handleSubmit()` |
605| `validateArrayFieldsStartingFrom(...)` | array methods run change validation unless `causeValidation: false` |
606| `validate(cause)` | `validate('change' \| 'blur')`, which runs form-level validators only |
607| `getAllErrors()` | `form.state.errors`, `field.errors`, `form.state.isValid`, or the `handleSubmit()` result |
608| `setErrorMap(errorMap)` | errors returned from validators, `createValidationError(...)` from `onSubmit`, or `serverState` |
609| `deleteField(name)` | `removeFieldValue` / `filterFieldValues` for array items, `setFieldValue` on the parent object |
610| `getFieldInfo(name)` | none; it exposed internal field registration |
611| `parseValuesWithSchema(schema)` and its `Async` variant | a schema validator plus `schemaOutputs` in `onSubmit`, or call the schema directly |
612| `getFormGroupMeta(name)` | `group.state` from `form.FormGroup` |
613​
614### Field metadata
615​
616v1 code often wrote field meta directly, for example to mark a field as touched
617when its value was set programmatically. In v2, meta is derived from updates.
618Pass `FieldUpdateOptions` to `setFieldValue`, the array methods, or
619`field.handleChange` to control what an update marks:
620​
621```tsx
622// v1
623form.setFieldValue('firstName', 'Ada', {
624 dontUpdateMeta: true,
625 dontValidate: true,
626})
627form.setFieldMeta('firstName', (prev) => ({ ...prev, isTouched: true }))
628```
629​
630```tsx
631// v2
632form.setFieldValue('firstName', 'Ada', {
633 markAsTouched: true,
634 markAsDirty: false,
635 causeValidation: false,
636})
637```
638​
639| v1 update option | v2 update option |
640| ------------------ | -------------------------------------------- |
641| `dontUpdateMeta` | `markAsTouched: false`, `markAsDirty: false` |
642| `dontValidate` | `causeValidation: false` |
643| `dontRunListeners` | none |
644​
645To touch every field before showing errors, call `form.handleSubmit()`, which
646marks all registered fields as touched. To show errors without touching fields,
647configure `errorVisibility` instead.
648​
649Read meta from the field API, as `field.meta` in a render prop or with
650`useSelector(field.atom, (state) => state.meta)`. The form API does not look up
651meta by path.
652​
653To clear meta, `form.resetField(name)` and `field.reset()` reset one field's
654value and meta. To clear every field's meta but keep the values the user
655entered, reset the form to its current values without moving the default
656baseline:
657​
658```tsx
659form.reset(form.state.values, { updateDefaultValues: false })
660```
661​
662This also clears form-level errors, submission state, and dirty history.
663​
664### On-demand validation
665​
666v2 has no public method that validates a single field or every field outside
667submission. Express when a field validates through its validators instead:
668​
669- Use `triggers` to choose the events that run a validator.
670- Use `watchFields` to rerun a validator when another field changes, which
671 covers most v1 `validateField` calls made from another field's `onChange`.
672- Call `form.handleSubmit()` to validate every field and the form together.
673 Unlike `validateAllFields`, it also calls `onSubmit` when validation passes.
674 It resolves to the error results, so an empty array means everything is
675 valid.
676​
677`form.validate('change')` and `form.validate('blur')` still exist, but they run
678form-level validators only. Field validators do not run.
679​
680### Errors
681​
682v2 does not write error maps directly. Return errors from a validator, or from
683`onSubmit` with `createValidationError(...)` as shown in
684[Errors and submit results](#errors-and-submit-results). For server-rendered
685errors, pass `serverState` to `useForm`.
686​
687To read errors, `form.state.errors` holds form-level errors only. Errors routed
688to fields stay on the fields, available as `field.errors`. Use
689`form.state.isValid` to check both levels at once.
690​
691### Schemas
692​
693`parseValuesWithSchema` checked the current values against a schema without
694storing errors. To keep that behavior, call the schema yourself:
695​
696```tsx
697const result = await schema['~standard'].validate(form.state.values)
698​
699if (result.issues) {
700 // handle issues
702```
703​
704To validate with the schema and use its parsed output, add it to `validators`
705and read `schemaOutputs` in `onSubmit`, as described in
706[Standard schemas](#standard-schemas).
707​
708## Shared form options
709​
710For extracted components, v1 composition examples often use a custom
711`useAppForm` hook plus `withForm` from `createFormHook`. v2 still supports app
712form hooks, but `withForm` was removed. The smaller building block for shared
713defaults is `formOptions(...)`:
714​
715```tsx
716import { formOptions } from '@tanstack/react-form'
717​
718export const sharedFormOptions = formOptions({
719 defaultValues: {
720 firstName: '',
721 lastName: '',
722 address: {
723 street: '',
724 country: '',
725 },
726 },
727})
728​
729const form = useForm({
730 ...sharedFormOptions,
731 onSubmit: ({ value }) => {
732 console.log(value)
733 },
734})
735```
736​
737When typing extracted components, prefer the v2 public types covered in
738[Splitting forms](./splitting-forms):
739​
740```tsx
741import type { AnyReactFormApi, FieldWithValue } from '@tanstack/react-form'
742​
743function StringField({ field }: { field: FieldWithValue<string> }) {
744 return (
745 <input
746 value={field.value}
747 onChange={(event) => field.handleChange(event.target.value)}
748 />
749 )
751​
752function SubmitButton({ form }: { form: AnyReactFormApi }) {
753 return (
754 <form.Subscribe selector={(state) => [state.canSubmit, state.isSubmitting]}>
755 {([canSubmit, isSubmitting]) => (
756 <button type="submit" disabled={!canSubmit || isSubmitting}>
757 {isSubmitting ? '...' : 'Submit'}
758 </button>
759 )}
760 </form.Subscribe>
761 )
763```
764​
765`AnyReactFormApi` and `FieldWithValue<T>` intentionally erase unrelated type
766details for generic UI pieces. Use `ReactFormType<typeof formOpts>` when a
767component needs the option-derived data and field-path surface. Options created
768with `appFormOptions` also retain their app component map. Submit error types
769may intentionally widen when the shared options omit `onSubmit` so it can be
770supplied later. Prefer these aliases over spelling the full `FormApi` or
771`FieldApi` generic lists in application components.
772​
773For components that previously used `withForm`, pass the form API explicitly and
774type it from the same options object:
775​
776```tsx
777// v1
778const AddressFields = withForm({
779 defaultValues: {
780 address: {
781 street: '',
782 country: '',
783 },
784 },
785 render: ({ form }) => (
786 <>
787 <form.Field name="address.street">{/* ... */}</form.Field>
788 <form.Field name="address.country">{/* ... */}</form.Field>
789 </>
790 ),
791})
792```
793​
794```tsx
795// v2
796import { formOptions } from '@tanstack/react-form'
797import type { ReactFormType } from '@tanstack/react-form'
798​
799export const profileFormOptions = formOptions({
800 defaultValues: {
801 address: {
802 street: '',
803 country: '',
804 },
805 },
806})
807​
808interface AddressFieldsProps {
809 form: ReactFormType<typeof profileFormOptions>
811​
812function AddressFields({ form }: AddressFieldsProps) {
813 return (
814 <>
815 <form.Field name="address.street">{/* ... */}</form.Field>
816 <form.Field name="address.country">{/* ... */}</form.Field>
817 </>
818 )
820```
821​
822## Form groups and field groups
823​
824Replace v1 form group usage with `form.FormGroup`. It is the v2 tool for
825multi-step forms and scoped validation when a section is part of one concrete
826form shape:
827​
828```tsx
829<form.FormGroup name="guestDetails" onSubmit={() => goToNextStep()}>
830 {(group) => (
831 <>
832 <group.Field name="name">
833 {(field) => (
834 <input
835 value={field.value}
836 onChange={(event) => field.handleChange(event.target.value)}
837 />
838 )}
839 </group.Field>
840 <button type="button" onClick={() => group.handleSubmit()}>
841 Continue
842 </button>
843 </>
844 )}
845</form.FormGroup>
846```
847​
848Inside the group, field names are scoped. `name="name"` becomes
849`guestDetails.name`, `group.ArrayField name="guests"` becomes
850`guestDetails.guests`, and watched fields are scoped the same way.
851​
852Group submission is its own validation cycle. `group.handleSubmit()` validates
853the group and its fields and then calls the group's `onSubmit` or
854`onSubmitInvalid`; `form.handleSubmit()` does not also run the group's
855validators. Keep any rules required for final whole-form submission in the
856form-level validator pipeline as well. `group.handleSubmit()` resolves to an
857error array, and `group.state.errors` is an array.
858​
859For a field inside a mounted group, scalar state exposed to `errorVisibility`
860(such as `submissionAttempts` and `isDirty`) is scoped to the nearest group.
861The callback's `values` and `errors` remain form-wide.
862​
863v1's `withFieldGroup` HOC was removed. v2 replaces it with
864`defineFieldGroup(...)` for reusable field bundles. Use it when a component
865should not care where its fields live in the parent form:
866​
867```tsx
868import { defineFieldGroup } from '@tanstack/react-form'
869​
870const rangeFieldGroup = defineFieldGroup(({ strict }) => ({
871 lower: strict<string>(),
872 upper: strict<string>(),
873}))
874​
875function RangeFieldsImpl({
876 fields,
877}: {
878 fields: typeof rangeFieldGroup.fields
879}) {
880 return (
881 <>
882 <fields.Field name="lower">
883 {(field) => (
884 <input
885 value={field.value}
886 onChange={(event) => field.handleChange(event.target.value)}
887 />
888 )}
889 </fields.Field>
890 <fields.Field
891 name="upper"
892 validators={[
893 {
894 triggers: ['change'],
895 watchFields: ['lower'],
896 run: ({ value }) => {
897 const lower = fields.getFieldValue('lower')
898 if (Number(value) < Number(lower)) {
899 return 'Upper bound must be greater than lower bound'
900 }
901 },
902 },
903 ]}
904 >
905 {(field) => (
906 <input
907 value={field.value}
908 onChange={(event) => field.handleChange(event.target.value)}
909 />
910 )}
911 </fields.Field>
912 </>
913 )
915​
916export const RangeFields = rangeFieldGroup.bindComponent(
917 RangeFieldsImpl,
918 'fields',
920```
921​
922Then bind virtual names to concrete paths wherever the group is used:
923​
924```tsx
925<RangeFields
926 form={form}
927 fields={{
928 lower: 'minPrice',
929 upper: 'maxPrice',
930 }}
931/>
932```
933​
934Use this v2 pattern to migrate v1 `withFieldGroup` components that were reused
935against different field paths. If you are using app form components from
936`createFormHook`, wrap components that expect an injected field API with
937`getFormHookHelpers()`, then define field groups with `defineAppFieldGroup`:
938​
939```tsx
940import { createFormHook, getFormHookHelpers } from '@tanstack/react-form'
941​
942const { fieldComponent } = getFormHookHelpers()
943const AppTextField = fieldComponent.strict(StringField, 'field')
944​
945const { appFormOptions, useAppForm, defineAppFieldGroup } = createFormHook({
946 fieldComponents: {
947 TextField: AppTextField,
948 },
949 formComponents: {},
950})
951​
952const contactFieldGroup = defineAppFieldGroup(({ strict }) => ({
953 name: strict<string>(),
954}))
955```
956​
957## Listeners
958​
959v1 listeners were event-keyed objects. v2 listeners use a validator-like array
960shape with `run`, `triggers`, and optional `triggerDebounceMs`. A trigger can be
961a string or `{ trigger, when }`, and debounce can be a number or a callback.
962Form listeners support `change`, `blur`, `submit`, `mount`, and `reset`; field
963listeners additionally support `unmount`.
964​
965```tsx
966// v2
967<form.Field
968 name="amount"
969 listeners={[
970 {
971 triggers: ['blur'],
972 run: ({ value, fieldApi }) => {
973 fieldApi.handleChange(Number(value).toFixed(2))
974 },
975 },
976 ]}
977/>
978```
979​
980For cross-field field listeners, put the source fields in `watchFields`. In
981`form.FormGroup` and field-group-bound components, `watchFields` uses the scoped
982or virtual field names and v2 resolves them to the concrete form paths.
983Form-level listeners instead observe propagated events and receive an optional
984source field as `triggerFieldApi`. It is present for propagated field changes
985and blurs, but absent for form-originated events such as mount, reset, and
986submit.
987​
988## Server and framework integrations
989​
990The v1 examples include Next server actions, Remix, and TanStack Start examples
991that use v1's keyed validators and store-level errors. The v2 examples show a
992new server-validation model in `@tanstack/react-form-start` and a Next.js
993example with shared isomorphic validation.
994​
995Key changes:
996​
997- Import `serverValidateHelper` from `@tanstack/react-form`, then import the
998 framework adapter from `@tanstack/react-form-start`,
999 `@tanstack/react-form-nextjs`.
1000- Share common form configuration with `formOptions(...)`.
1001- Return the `createErrorMap()` map directly from framework/server validators
1002 when routing form and field errors.
1003- Combine `triggers: ['server']` with `skipOnSubmit: true` for a form validator
1004 that must run only on the server. Server-triggered validators otherwise still
1005 run during client submission because submission is enabled by default.
1006- Next.js and Remix adapters, and the Start adapter when no callback override is
1007 supplied, resolve to
1008 `{ success: true, values, schemaOutputs }` or
1009 `{ success: false, serverState }`. Pass the failure's `serverState` back to
1010 `useForm({ ...formOpts, serverState })` on the client.
1011- `@tanstack/react-form-remix` was removed.
1012​
1013For example, a Start adapter is configured separately from the shared form
1014options:
1015​
1016```tsx
1017import { serverValidateHelper } from '@tanstack/react-form'
1018import { start } from '@tanstack/react-form-start'
1019​
1020const { createServerValidate } = serverValidateHelper({
1021 framework: start(),
1023​
1024const serverValidate = createServerValidate(formOpts)
1025```
1026​
1027In `formOpts`, a server-only validator returns its routed error map directly:
1028​
1029```tsx
1031 triggers: ['server'],
1032 skipOnSubmit: true,
1033 run: ({ value, createErrorMap }) => {
1034 const errors = createErrorMap()
1035​
1036 if (value.age < 13) {
1037 errors.fields.age = 'You must be at least 13'
1039​
1040 return errors
1041 },
1043```
1044​
1045Client rendering still follows the same v2 field surface:
1046​
1047```tsx
1048<form.Field name="age">
1049 {(field) => (
1050 <>
1051 <input
1052 name={field.name}
1053 value={field.value}
1054 onBlur={field.handleBlur}
1055 onChange={(event) => field.handleChange(Number(event.target.value))}
1056 />
1057 {field.errors.map((error) => (
1058 <div key={error.message} role="alert">
1059 {error.message}
1060 </div>
1061 ))}
1062 </>
1063 )}
1064</form.Field>
1065```
1066​
1067## Migration order for an app
1068​
10691. Upgrade imports and keep the smallest possible form compiling with
1070 ESM `import` syntax, `useForm`, `defaultValues`, `form.Field`, and
1071 `form.handleSubmit()`.
10722. Move every field-level `defaultValue` into form-level `defaultValues` and
1073 remove `defaultMeta`.
10743. Update field render props from `field.state.*` to the direct v2 surface.
10754. Replace `useStore(...store...)` with `useSelector(...atom...)`.
10765. Convert validators and listeners to arrays, paying special attention to the
1077 default submit behavior.
10786. Convert arrays from `mode="array"` to `form.ArrayField`; keep relative
1079 mutators on its render prop or move them to path-based form methods.
10807. Return `createErrorMap(...)` directly from form, group, and server validators,
1081 and convert submitted endpoint errors to `createValidationError(...)`.
10828. Revisit composition: use `formOptions(...)` for shared options,
1083 `ReactFormType<typeof formOpts>` for extracted form props,
1084 `form.FormGroup` for scoped sections, and
1085 `defineFieldGroup(...).bindComponent(...)` for reusable field bundles.
10869. Re-run React integration tests around validation timing, field rerenders,
1087 groups, server error hydration, and array mutations. These are the areas
1088 where v2 intentionally tightened behavior.