Open History to see the last commit
1---
2id: form-composition
3title: Form Composition
4---
5β
6A common criticism of TanStack Form is that it is verbose out-of-the-box. While this verbosity _can_ be useful for educational purposes - helping to enforce understanding of our APIs - it's not ideal in production use cases.
7β
8As a result, while `form.Field` enables the most powerful and flexible usage of TanStack Form, we provide APIs that wrap it and make your application code less verbose.
9β
10## Custom Form Hooks
11β
12The most powerful way to compose forms is to create custom form hooks. This allows you to create a form hook that is tailored to your application's needs, including pre-bound custom UI components and more.
13β
14At it's most basic, `createFormHook` is a function that takes a `fieldContext` and `formContext` and returns a `useAppForm` hook.
15β
16> This un-customized `useAppForm` hook is identical to `useForm`, but that will quickly change as we add more options to `createFormHook`.
17β
18```tsx AppFormContext.tsx
19import { createFormHookContexts } from '@tanstack/react-form'
20β
21// export useFieldContext for use in your custom components
22export const { fieldContext, formContext, useFieldContext } =
23 createFormHookContexts()
24```
25β
26```tsx AppForm.tsx
27import { createFormHook } from '@tanstack/react-form'
28import { createFormHookContexts } from './AppFormContext'
29β
30const { useAppForm } = createFormHook({
31 fieldContext,
32 formContext,
33 // We'll learn more about these options later
34 fieldComponents: {},
35 formComponents: {},
36})
37β
38function App() {
39 const form = useAppForm({
40 // Supports all useForm options
41 defaultValues: {
42 firstName: 'John',
43 lastName: 'Doe',
44 },
45 })
46β
47 return <form.Field /> // ...
48}
49```
50β
51### Pre-bound Field Components
52β
53Once this scaffolding is in place, you can start adding custom field and form components to your form hook.
54β
55> Note: the `useFieldContext` must be the same one exported from your custom form context
56β
57```tsx
58import { useFieldContext } from './form-context.tsx'
59β
60export function TextField({ label }: { label: string }) {
61 // The `Field` infers that it should have a `value` type of `string`
62 const field = useFieldContext<string>()
63 return (
64 <label>
65 <span>{label}</span>
66 <input
67 value={field.state.value}
68 onChange={(e) => field.handleChange(e.target.value)}
69 />
70 </label>
71 )
72}
73```
74β
75You're then able to register this component with your form hook.
76β
77```tsx
78import { TextField } from './text-field.tsx'
79β
80const { useAppForm } = createFormHook({
81 fieldContext,
82 formContext,
83 fieldComponents: {
84 TextField,
85 },
86 formComponents: {},
87})
88```
89β
90And use it in your form:
91β
92```tsx
93function App() {
94 const form = useAppForm({
95 defaultValues: {
96 firstName: 'John',
97 lastName: 'Doe',
98 },
99 })
100β
101 return (
102 // Notice the `AppField` instead of `Field`; `AppField` provides the required context
103 <form.AppField
104 name="firstName"
105 children={(field) => <field.TextField label="First Name" />}
106 />
107 )
108}
109```
110β
111This not only allows you to reuse the UI of your shared component, but retains the type-safety you'd expect from TanStack Form: Mistyping `firstName` will result in a TypeScript error.
112β
113#### A note on performance
114β
115While context is a valuable tool in the React ecosystem, there's appropriate concern from many users that providing a reactive value through a context will cause unnecessary re-renders.
116β
117> Unfamiliar with this performance concern? [Mark Erikson's blog post explaining why Redux solves many of these problems](https://blog.isquaredsoftware.com/2021/01/context-redux-differences/) is a great place to start.
118β
119While this is a good concern to call out, it's not a problem for TanStack Form; the values provided through context are not reactive themselves, but instead are static class instances with reactive properties ([using TanStack Store as our signals implementation to power the show](https://tanstack.com/store)).
120β
121### Pre-bound Form Components
122β
123While `form.AppField` solves many of the problems with Field boilerplate and reusability, it doesn't solve the problem of _form_ boilerplate and reusability.
124β
125In particular, being able to share instances of `form.Subscribe` for, say, a reactive form submission button is a common usecase.
126β
127```tsx
128function SubscribeButton({ label }: { label: string }) {
129 const form = useFormContext()
130 return (
131 <form.Subscribe selector={(state) => state.isSubmitting}>
132 {(isSubmitting) => (
133 <button type="submit" disabled={isSubmitting}>
134 {label}
135 </button>
136 )}
137 </form.Subscribe>
138 )
139}
140β
141const { useAppForm, withForm } = createFormHook({
142 fieldComponents: {},
143 formComponents: {
144 SubscribeButton,
145 },
146 fieldContext,
147 formContext,
148})
149β
150function App() {
151 const form = useAppForm({
152 defaultValues: {
153 firstName: 'John',
154 lastName: 'Doe',
155 },
156 })
157β
158 return (
159 <form.AppForm>
160 // Notice the `AppForm` component wrapper; `AppForm` provides the required
161 context
162 <form.SubscribeButton label="Submit" />
163 </form.AppForm>
164 )
165}
166```
167β
168### Extending custom appForm
169β
170It is quite common for platform teams to ship pre built appForms. It can be exported from a library in a monorepo or as a standalone package on npm.
171β
172```tsx weyland-yutan-corp/forms-context.tsx
173export const { fieldContext, formContext, useFieldContext, useFormContext } =
174 createFormHookContexts()
175```
176β
177```tsx weyland-yutan-corp/forms.tsx
178import { createFormHook } from '@tanstack/react-form'
179import { fieldContext, formContext } from 'weyland-yutan-corp/forms-context'
180β
181// fields
182import { UserIdField } from './FieldComponents/UserIdField'
183β
184// components
185import { SubmitButton } from './FormComponents/SubmitButton'
186β
187const ProfileForm = createFormHook({
188 fieldContext,
189 formContext,
190 fieldComponents: { UserIdField },
191 formComponents: { SubmitButton },
192})
193β
194export default ProfileForm
195```
196β
197There is a situation that you might have a field exclusive to a downstream dev team, in such a case you can extend the AppForm like so.
198β
1991 - Create new AppForm fields
200β
201```tsx AppForm.tsx
202// imported from the same AppForm you want to extend
203import { useFieldContext } from 'weyland-yutan-corp/forms-context'
204β
205export function CustomTextField({ label }: { label: string }) {
206 const field = useFieldContext<string>()
207 return (
208 <div>
209 <label>{/* rest of component */}</label>
210 </div>
211 )
212}
213```
214β
2152 - Extend the AppForm
216β
217```tsx AppForm.tsx
218// notice the same import as above
219import ProfileForm from 'weyland-yutan-corp/forms'
220β
221import { CustomTextField } from './FieldComponents/CustomTextField'
222import { SubmitButton } from './FormComponents/SubmitButton'
223β
224export const { useAppForm } = ProfileForm.extendForm({
225 fieldComponents: { CustomTextField },
226 // Ts will error since the parent appForm already has a component called CustomSubmit
227 formComponents: { SubmitButton },
228})
229```
230β
231This way you can add extra fields that are unique to your team without bloating the upstream AppForm.
232β
233## Breaking big forms into smaller pieces
234β
235Sometimes forms get very large; it's just how it goes sometimes. While TanStack Form supports large forms well, it's never fun to work with hundreds or thousands of lines of code in single files.
236β
237To solve this, we support breaking forms into smaller pieces using the `withForm` higher-order component.
238β
239```tsx
240const { useAppForm, withForm } = createFormHook({
241 fieldComponents: {
242 TextField,
243 },
244 formComponents: {
245 SubscribeButton,
246 },
247 fieldContext,
248 formContext,
249})
250β
251const ChildForm = withForm({
252 // These values are only used for type-checking, and are not used at runtime
253 // This allows you to `...formOpts` from `formOptions` without needing to redeclare the options
254 defaultValues: {
255 firstName: 'John',
256 lastName: 'Doe',
257 },
258 // Optional, but adds props to the `render` function in addition to `form`
259 props: {
260 // These props are also set as default values for the `render` function
261 title: 'Child Form',
262 },
263 render: function Render({ form, title }) {
264 return (
265 <div>
266 <p>{title}</p>
267 <form.AppField
268 name="firstName"
269 children={(field) => <field.TextField label="First Name" />}
270 />
271 <form.AppForm>
272 <form.SubscribeButton label="Submit" />
273 </form.AppForm>
274 </div>
275 )
276 },
277})
278β
279function App() {
280 const form = useAppForm({
281 defaultValues: {
282 firstName: 'John',
283 lastName: 'Doe',
284 },
285 })
286β
287 return <ChildForm form={form} title={'Testing'} />
288}
289```
290β
291> Something worth mentioning, is that while multiple chaining of `AppForm` extensions is possible it is can lead to decreases in TypeScript performance.
292> For most users that may only extend an appForm once this isn't a problem, however we recommend limiting it to 3-5 extensions.
293β
294### `withForm` FAQ
295β
296> Why a higher-order component instead of a hook?
297β
298While hooks are the future of React, higher-order components are still a powerful tool for composition. In particular, the API of `withForm` enables us to have strong type-safety without requiring users to pass generics.
299β
300> Why am I getting ESLint errors about hooks in `render`?
301β
302ESLint looks for hooks in the top-level of a function, and `render` may not be recogized as a top-level component, depending on how you defined it.
303β
304```tsx
305// This will cause ESLint errors with hooks usage
306const ChildForm = withForm({
307 // ...
308 render: ({ form, title }) => {
309 // ...
310 },
311})
312```
313β
314```tsx
315// This works fine
316const ChildForm = withForm({
317 // ...
318 render: function Render({ form, title }) {
319 // ...
320 },
321})
322```
323β
324### Context as a last resort
325β
326There are cases where passing `form` with `withForm` is not feasible. You may encounter it with components that don't
327allow you to change their props.
328β
329For example, consider the following TanStack Router usage:
330β
331```ts
332function RouteComponent() {
333 const form = useAppForm({...formOptions, /* ... */ })
334 // <Outlet /> cannot be customized or receive additional props
335 return <Outlet />
336}
337```
338β
339In edge cases like this, a context-based fallback is available to access the form instance.
340β
341```ts
342const { useAppForm, useTypedAppFormContext } = createFormHook({
343 fieldContext,
344 formContext,
345 fieldComponents: {},
346 formComponents: {},
347})
348```
349β
350> [!IMPORTANT] Type safety
351> This mechanism exists solely to bridge integration constraints and should be avoided whenever `withForm` is possible.
352> Context will not warn you when the types do not align. You risk runtime errors with this implementation.
353β
354Usage:
355β
356```tsx
357// sharedOpts.ts
358const formOpts = formOptions({
359 /* ... */
360})
361β
362function ParentComponent() {
363 const form = useAppForm({ ...formOptions /* ... */ })
364β
365 return (
366 <form.AppForm>
367 <ChildComponent />
368 </form.AppForm>
369 )
370}
371β
372function ChildComponent() {
373 const form = useTypedAppFormContext({ ...formOptions })
374β
375 // You now have access to form components, field components and fields
376}
377```
378β
379## Reusing groups of fields in multiple forms
380β
381Sometimes, a pair of fields are so closely related that it makes sense to group and reuse them β like the password example listed in the [linked fields guide](./linked-fields.md). Instead of repeating this logic across multiple forms, you can utilize the `withFieldGroup` higher-order component.
382β
383> Unlike `withForm`, validators cannot be specified and could be any value.
384> Ensure that your fields can accept unknown error types.
385β
386Rewriting the passwords example using `withFieldGroup` would look like this:
387β
388```tsx
389const { useAppForm, withForm, withFieldGroup } = createFormHook({
390 fieldComponents: {
391 TextField,
392 ErrorInfo,
393 },
394 formComponents: {
395 SubscribeButton,
396 },
397 fieldContext,
398 formContext,
399})
400β
401type PasswordFields = {
402 password: string
403 confirm_password: string
404}
405β
406// These default values are not used at runtime, but the keys are needed for mapping purposes.
407// This allows you to spread `formOptions` without needing to redeclare it.
408const defaultValues: PasswordFields = {
409 password: '',
410 confirm_password: '',
411}
412β
413const FieldGroupPasswordFields = withFieldGroup({
414 defaultValues,
415 // You may also restrict the group to only use forms that implement this submit meta.
416 // If none is provided, any form with the right defaultValues may use it.
417 // onSubmitMeta: { action: '' }
418β
419 // Optional, but adds props to the `render` function in addition to `form`
420 props: {
421 // These default values are also for type-checking and are not used at runtime
422 title: 'Password',
423 },
424 // Internally, you will have access to a `group` instead of a `form`
425 render: function Render({ group, title }) {
426 // access reactive values using the group store
427 const password = useStore(group.store, (state) => state.values.password)
428 // or the form itself
429 const isSubmitting = useStore(
430 group.form.store,
431 (state) => state.isSubmitting,
432 )
433β
434 return (
435 <div>
436 <h2>{title}</h2>
437 {/* Groups also have access to Field, Subscribe, Field, AppField and AppForm */}
438 <group.AppField name="password">
439 {(field) => <field.TextField label="Password" />}
440 </group.AppField>
441 <group.AppField
442 name="confirm_password"
443 validators={{
444 onChangeListenTo: ['password'],
445 onChange: ({ value, fieldApi }) => {
446 // The form could be any values, so it is typed as 'unknown'
447 const values: unknown = fieldApi.form.state.values
448 // use the group methods instead
449 if (value !== group.getFieldValue('password')) {
450 return 'Passwords do not match'
451 }
452 return undefined
453 },
454 }}
455 >
456 {(field) => (
457 <div>
458 <field.TextField label="Confirm Password" />
459 <field.ErrorInfo />
460 </div>
461 )}
462 </group.AppField>
463 </div>
464 )
465 },
466})
467```
468β
469We can now use these grouped fields in any form that implements the default values:
470β
471```tsx
472// You are allowed to extend the group fields as long as the
473// existing properties remain unchanged
474type Account = PasswordFields & {
475 provider: string
476 username: string
477}
478β
479// You may nest the group fields wherever you want
480type FormValues = {
481 name: string
482 age: number
483 account_data: PasswordFields
484 linked_accounts: Account[]
485}
486β
487const defaultValues: FormValues = {
488 name: '',
489 age: 0,
490 account_data: {
491 password: '',
492 confirm_password: '',
493 },
494 linked_accounts: [
495 {
496 provider: 'TanStack',
497 username: '',
498 password: '',
499 confirm_password: '',
500 },
501 ],
502}
503β
504function App() {
505 const form = useAppForm({
506 defaultValues,
507 // If the group didn't specify an `onSubmitMeta` property,
508 // the form may implement any meta it wants.
509 // Otherwise, the meta must be defined and match.
510 onSubmitMeta: { action: '' },
511 })
512β
513 return (
514 <form.AppForm>
515 <FieldGroupPasswordFields
516 form={form}
517 // You must specify where the fields can be found
518 fields="account_data"
519 title="Passwords"
520 />
521 <form.Field name="linked_accounts" mode="array">
522 {(field) =>
523 field.state.value.map((account, i) => (
524 <FieldGroupPasswordFields
525 key={account.provider}
526 form={form}
527 // The fields may be in nested fields
528 fields={`linked_accounts[${i}]`}
529 title={account.provider}
530 />
531 ))
532 }
533 </form.Field>
534 </form.AppForm>
535 )
536}
537```
538β
539### Mapping field group values to a different field
540β
541You may want to keep the password fields on the top level of your form, or rename the properties for clarity. You can map field group values
542to their true location by changing the `field` property:
543β
544> [!IMPORTANT]
545> Due to TypeScript limitations, field mapping is only allowed for objects. You can use records or arrays at the top level of a field group, but you will not be able to map the fields.
546β
547```tsx
548// To have an easier form, you can keep the fields on the top level
549type FormValues = {
550 name: string
551 age: number
552 password: string
553 confirm_password: string
554}
555β
556const defaultValues: FormValues = {
557 name: '',
558 age: 0,
559 password: '',
560 confirm_password: '',
561}
562β
563function App() {
564 const form = useAppForm({
565 defaultValues,
566 })
567β
568 return (
569 <form.AppForm>
570 <FieldGroupPasswordFields
571 form={form}
572 // You can map the fields to their equivalent deep key
573 fields={{
574 password: 'password',
575 confirm_password: 'confirm_password',
576 // or map them to differently named keys entirely
577 // 'password': 'name'
578 }}
579 title="Passwords"
580 />
581 </form.AppForm>
582 )
583}
584```
585β
586If you expect your fields to always be at the top level of your form, you can create a quick map
587of your field groups using a helper function:
588β
589```tsx
590const defaultValues: PasswordFields = {
591 password: '',
592 confirm_password: '',
593}
594β
595const passwordFields = createFieldMap(defaultValues)
596/* This generates the following map:
597 {
598 'password': 'password',
599 'confirm_password': 'confirm_password'
600 }
601*/
602β
603// Usage:
604<FieldGroupPasswordFields
605 form={form}
606 fields={passwordFields}
607 title="Passwords"
608/>
609```
610β
611## Tree-shaking form and field components
612β
613While the above examples are great for getting started, they're not ideal for certain use-cases where you might have hundreds of form and field components.
614In particular, you may not want to include all of your form and field components in the bundle of every file that uses your form hook.
615β
616To solve this, you can mix the `createFormHook` TanStack API with the React `lazy` and `Suspense` components:
617β
618```typescript
619// src/hooks/form-context.ts
620import { createFormHookContexts } from '@tanstack/react-form'
621β
622export const { fieldContext, useFieldContext, formContext, useFormContext } =
623 createFormHookContexts()
624```
625β
626```tsx
627// src/components/text-field.tsx
628import { useFieldContext } from '../hooks/form-context.tsx'
629β
630export default function TextField({ label }: { label: string }) {
631 const field = useFieldContext<string>()
632β
633 return (
634 <label>
635 <span>{label}</span>
636 <input
637 value={field.state.value}
638 onChange={(e) => field.handleChange(e.target.value)}
639 />
640 </label>
641 )
642}
643```
644β
645```tsx
646// src/hooks/form.ts
647import { lazy } from 'react'
648import { createFormHook } from '@tanstack/react-form'
649β
650const TextField = lazy(() => import('../components/text-fields.tsx'))
651β
652const { useAppForm, withForm } = createFormHook({
653 fieldContext,
654 formContext,
655 fieldComponents: {
656 TextField,
657 },
658 formComponents: {},
659})
660```
661β
662```tsx
663// src/App.tsx
664import { Suspense } from 'react'
665import { PeoplePage } from './features/people/form.tsx'
666β
667export default function App() {
668 return (
669 <Suspense fallback={<p>Loading...</p>}>
670 <PeoplePage />
671 </Suspense>
672 )
673}
674```
675β
676This will show the Suspense fallback while the `TextField` component is being loaded, and then render the form once it's loaded.
677β
678## Putting it all together
679β
680Now that we've covered the basics of creating custom form hooks, let's put it all together in a single example.
681β
682```tsx
683// /src/hooks/form.ts, to be used across the entire app
684const { fieldContext, useFieldContext, formContext, useFormContext } =
685 createFormHookContexts()
686β
687function TextField({ label }: { label: string }) {
688 const field = useFieldContext<string>()
689 return (
690 <label>
691 <span>{label}</span>
692 <input
693 value={field.state.value}
694 onChange={(e) => field.handleChange(e.target.value)}
695 />
696 </label>
697 )
698}
699β
700function SubscribeButton({ label }: { label: string }) {
701 const form = useFormContext()
702 return (
703 <form.Subscribe selector={(state) => state.isSubmitting}>
704 {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
705 </form.Subscribe>
706 )
707}
708β
709const { useAppForm, withForm } = createFormHook({
710 fieldComponents: {
711 TextField,
712 },
713 formComponents: {
714 SubscribeButton,
715 },
716 fieldContext,
717 formContext,
718})
719β
720// /src/features/people/shared-form.ts, to be used across `people` features
721const formOpts = formOptions({
722 defaultValues: {
723 firstName: 'John',
724 lastName: 'Doe',
725 },
726})
727β
728// /src/features/people/nested-form.ts, to be used in the `people` page
729const ChildForm = withForm({
730 ...formOpts,
731 // Optional, but adds props to the `render` function outside of `form`
732 props: {
733 title: 'Child Form',
734 },
735 render: ({ form, title }) => {
736 return (
737 <div>
738 <p>{title}</p>
739 <form.AppField
740 name="firstName"
741 children={(field) => <field.TextField label="First Name" />}
742 />
743 <form.AppForm>
744 <form.SubscribeButton label="Submit" />
745 </form.AppForm>
746 </div>
747 )
748 },
749})
750β
751// /src/features/people/page.ts
752const Parent = () => {
753 const form = useAppForm({
754 ...formOpts,
755 })
756β
757 return <ChildForm form={form} title={'Testing'} />
758}
759```
760β
761## API Usage Guidance
762β
763Here's a chart to help you decide what APIs you should be using:
764β
765