Open History to see the last commit
1---
2id: form-composition
3title: Form Composition
4---
5β
6A common criticism of TanStack Form is its verbosity out-of-the-box. While this _can_ be useful for educational purposes - helping enforce understanding 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
19import { createFormHookContexts, createFormHook } from '@tanstack/react-form'
20β
21// export useFieldContext for use in your custom components
22export const { fieldContext, formContext, useFieldContext } =
23 createFormHookContexts()
24β
25const { useAppForm } = createFormHook({
26 fieldContext,
27 formContext,
28 // We'll learn more about these options later
29 fieldComponents: {},
30 formComponents: {},
31})
32β
33function App() {
34 const form = useAppForm({
35 // Supports all useForm options
36 defaultValues: {
37 firstName: 'John',
38 lastName: 'Doe',
39 },
40 })
41β
42 return <form.Field /> // ...
43}
44```
45β
46### Pre-bound Field Components
47β
48Once this scaffolding is in place, you can start adding custom field and form components to your form hook.
49β
50> Note: the `useFieldContext` must be the same one exported from your custom form context
51β
52```tsx
53import { useFieldContext } from './form-context.tsx'
54β
55export function TextField({ label }: { label: string }) {
56 // The `Field` infers that it should have a `value` type of `string`
57 const field = useFieldContext<string>()
58 return (
59 <label>
60 <div>{label}</div>
61 <input
62 value={field.state.value}
63 onChange={(e) => field.handleChange(e.target.value)}
64 />
65 </label>
66 )
67}
68```
69β
70You're then able to register this component with your form hook.
71β
72```tsx
73import { TextField } from './text-field.tsx'
74β
75const { useAppForm } = createFormHook({
76 fieldContext,
77 formContext,
78 fieldComponents: {
79 TextField,
80 },
81 formComponents: {},
82})
83```
84β
85And use it in your form:
86β
87```tsx
88function App() {
89 const form = useAppForm({
90 defaultValues: {
91 firstName: 'John',
92 lastName: 'Doe',
93 },
94 })
95β
96 return (
97 // Notice the `AppField` instead of `Field`; `AppField` provides the required context
98 <form.AppField
99 name="firstName"
100 children={(field) => <field.TextField label="First Name" />}
101 />
102 )
103}
104```
105β
106This not only allows you to reuse the UI of your shared component, but retains the type-safety you'd expect from TanStack Form: Typo `name` and get a TypeScript error.
107β
108#### A note on performance
109β
110While 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.
111β
112> 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.
113β
114While 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)).
115β
116### Pre-bound Form Components
117β
118While `form.AppField` solves many of the problems with Field boilerplate and reusability, it doesn't solve the problem of _form_ boilerplate and reusability.
119β
120In particular, being able to share instances of `form.Subscribe` for, say, a reactive form submission button is a common usecase.
121β
122```tsx
123function SubscribeButton({ label }: { label: string }) {
124 const form = useFormContext()
125 return (
126 <form.Subscribe selector={(state) => state.isSubmitting}>
127 {(isSubmitting) => (
128 <button type="submit" disabled={isSubmitting}>
129 {label}
130 </button>
131 )}
132 </form.Subscribe>
133 )
134}
135β
136const { useAppForm, withForm } = createFormHook({
137 fieldComponents: {},
138 formComponents: {
139 SubscribeButton,
140 },
141 fieldContext,
142 formContext,
143})
144β
145function App() {
146 const form = useAppForm({
147 defaultValues: {
148 firstName: 'John',
149 lastName: 'Doe',
150 },
151 })
152β
153 return (
154 <form.AppForm>
155 // Notice the `AppForm` component wrapper; `AppForm` provides the required
156 context
157 <form.SubscribeButton label="Submit" />
158 </form.AppForm>
159 )
160}
161```
162β
163## Breaking big forms into smaller pieces
164β
165Sometimes 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 long files.
166β
167To solve this, we support breaking forms into smaller pieces using the `withForm` higher-order component.
168β
169```tsx
170const { useAppForm, withForm } = createFormHook({
171 fieldComponents: {
172 TextField,
173 },
174 formComponents: {
175 SubscribeButton,
176 },
177 fieldContext,
178 formContext,
179})
180β
181const ChildForm = withForm({
182 // These values are only used for type-checking, and are not used at runtime
183 // This allows you to `...formOpts` from `formOptions` without needing to redeclare the options
184 defaultValues: {
185 firstName: 'John',
186 lastName: 'Doe',
187 },
188 // Optional, but adds props to the `render` function in addition to `form`
189 props: {
190 // These props are also set as default values for the `render` function
191 title: 'Child Form',
192 },
193 render: function Render({ form, title }) {
194 return (
195 <div>
196 <p>{title}</p>
197 <form.AppField
198 name="firstName"
199 children={(field) => <field.TextField label="First Name" />}
200 />
201 <form.AppForm>
202 <form.SubscribeButton label="Submit" />
203 </form.AppForm>
204 </div>
205 )
206 },
207})
208β
209function App() {
210 const form = useAppForm({
211 defaultValues: {
212 firstName: 'John',
213 lastName: 'Doe',
214 },
215 })
216β
217 return <ChildForm form={form} title={'Testing'} />
218}
219```
220β
221### `withForm` FAQ
222β
223> Why a higher-order component instead of a hook?
224β
225While hooks are the future of React, higher-order components are still a powerful tool for composition. In particular, the API of `useForm` enables us to have strong type-safety without requiring users to pass generics.
226β
227> Why am I getting ESLint errors about hooks in `render`?
228β
229ESLint 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.
230β
231```tsx
232// This will cause ESLint errors with hooks usage
233const ChildForm = withForm({
234 // ...
235 render: ({ form, title }) => {
236 // ...
237 },
238})
239```
240β
241```tsx
242// This works fine
243const ChildForm = withForm({
244 // ...
245 render: function Render({ form, title }) {
246 // ...
247 },
248})
249```
250β
251## Tree-shaking form and field components
252β
253While 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.
254In 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.
255β
256To solve this, you can mix the `createFormHook` TanStack API with the React `lazy` and `Suspense` components:
257β
258```typescript
259// src/hooks/form-context.ts
260import { createFormHookContexts } from '@tanstack/react-form'
261β
262export const { fieldContext, useFieldContext, formContext, useFormContext } =
263 createFormHookContexts()
264```
265β
266```tsx
267// src/components/text-field.tsx
268import { useFieldContext } from '../hooks/form-context.tsx'
269β
270export default function TextField({ label }: { label: string }) {
271 const field = useFieldContext<string>()
272β
273 return (
274 <label>
275 <div>{label}</div>
276 <input
277 value={field.state.value}
278 onChange={(e) => field.handleChange(e.target.value)}
279 />
280 </label>
281 )
282}
283```
284β
285```tsx
286// src/hooks/form.ts
287import { lazy } from 'react'
288import { createFormHook } from '@tanstack/react-form'
289β
290const TextField = lazy(() => import('../components/text-fields.tsx'))
291β
292const { useAppForm, withForm } = createFormHook({
293 fieldContext,
294 formContext,
295 fieldComponents: {
296 TextField,
297 },
298 formComponents: {},
299})
300```
301β
302```tsx
303// src/App.tsx
304import { Suspense } from 'react'
305import { PeoplePage } from './features/people/page.tsx'
306β
307export default function App() {
308 return (
309 <Suspense fallback={<p>Loading...</p>}>
310 <PeopleForm />
311 </Suspense>
312 )
313}
314```
315β
316This will show the Suspense fallback while the `TextField` component is being loaded, and then render the form once it's loaded.
317β
318## Putting it all together
319β
320Now that we've covered the basics of creating custom form hooks, let's put it all together in a single example.
321β
322```tsx
323// /src/hooks/form.ts, to be used across the entire app
324const { fieldContext, useFieldContext, formContext, useFormContext } =
325 createFormHookContexts()
326β
327function TextField({ label }: { label: string }) {
328 const field = useFieldContext<string>()
329 return (
330 <label>
331 <div>{label}</div>
332 <input
333 value={field.state.value}
334 onChange={(e) => field.handleChange(e.target.value)}
335 />
336 </label>
337 )
338}
339β
340function SubscribeButton({ label }: { label: string }) {
341 const form = useFormContext()
342 return (
343 <form.Subscribe selector={(state) => state.isSubmitting}>
344 {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
345 </form.Subscribe>
346 )
347}
348β
349const { useAppForm, withForm } = createFormHook({
350 fieldComponents: {
351 TextField,
352 },
353 formComponents: {
354 SubscribeButton,
355 },
356 fieldContext,
357 formContext,
358})
359β
360// /src/features/people/shared-form.ts, to be used across `people` features
361const formOpts = formOptions({
362 defaultValues: {
363 firstName: 'John',
364 lastName: 'Doe',
365 },
366})
367β
368// /src/features/people/nested-form.ts, to be used in the `people` page
369const ChildForm = withForm({
370 ...formOpts,
371 // Optional, but adds props to the `render` function outside of `form`
372 props: {
373 title: 'Child Form',
374 },
375 render: ({ form, title }) => {
376 return (
377 <div>
378 <p>{title}</p>
379 <form.AppField
380 name="firstName"
381 children={(field) => <field.TextField label="First Name" />}
382 />
383 <form.AppForm>
384 <form.SubscribeButton label="Submit" />
385 </form.AppForm>
386 </div>
387 )
388 },
389})
390β
391// /src/features/people/page.ts
392const Parent = () => {
393 const form = useAppForm({
394 ...formOpts,
395 })
396β
397 return <ChildForm form={form} title={'Testing'} />
398}
399```
400β
401## API Usage Guidance
402β
403Here's a chart to help you decide what APIs you should be using:
404β
405