Open History to see the last commit
1---
2id: basic-concepts
3title: Basic Concepts and Terminology
4---
5β
6This page introduces the basic concepts and terminology used in the `@tanstack/react-form` library. Familiarizing yourself with these concepts will help you better understand and work with the library.
7β
8## Form Options
9β
10You can create options for your form so that it can be shared between multiple forms by using the `formOptions` function.
11β
12Example:
13β
14```tsx
15const formOpts = formOptions<Person>({
16 defaultValues: {
17 firstName: '',
18 lastName: '',
19 hobbies: [],
20 },
21})
22```
23β
24## Form Instance
25β
26A Form Instance is an object that represents an individual form and provides methods and properties for working with the form. You create a form instance using the `useForm` hook provided by the form options. The hook accepts an object with an `onSubmit` function, which is called when the form is submitted.
27β
28```tsx
29const form = useForm({
30 ...formOpts,
31 onSubmit: async ({ value }) => {
32 // Do something with form data
33 console.log(value)
34 },
35})
36```
37β
38You may also create a form instance without using `formOptions` by using the standalone `useForm` API:
39β
40```tsx
41const form = useForm<Person>({
42 onSubmit: async ({ value }) => {
43 // Do something with form data
44 console.log(value)
45 },
46 defaultValues: {
47 firstName: '',
48 lastName: '',
49 hobbies: [],
50 },
51})
52```
53β
54## Field
55β
56A Field represents a single form input element, such as a text input or a checkbox. Fields are created using the form.Field component provided by the form instance. The component accepts a name prop, which should match a key in the form's default values. It also accepts a children prop, which is a render prop function that takes a field object as its argument.
57β
58Example:
59β
60```tsx
61<form.Field
62 name="firstName"
63 children={(field) => (
64 <>
65 <input
66 value={field.state.value}
67 onBlur={field.handleBlur}
68 onChange={(e) => field.handleChange(e.target.value)}
69 />
70 <FieldInfo field={field} />
71 </>
72 )}
73/>
74```
75β
76## Field State
77β
78Each field has its own state, which includes its current value, validation status, error messages, and other metadata. You can access a field's state using the `field.state` property.
79β
80Example:
81β
82```tsx
83const { value, error, touched, isValidating } = field.state
84```
85β
86There are three field states can be very useful to see how the user interacts with a field. A field is _"touched"_ when the user clicks/tabs into it, _"pristine"_ until the user changes value in it, and _"dirty"_ after the value has been changed. You can check these states via the `isTouched`, `isPristine` and `isDirty` flags, as seen below.
87β
88```tsx
89const { isTouched, isPristine, isDirty } = field.state.meta
90```
91β
92
93β
94> **Important note for users coming from `React Hook Form`**: the `isDirty` flag in `TanStack/form` is different from the flag with the same name in RHF.
95> In RHF, `isDirty = true`, when the form's values are different from the original values. If the user changes the values in a form, and then changes them again to end up with values that match the form's default values, `isDirty` will be `false` in RHF, but `true` in `TanStack/form`.
96> The default values are exposed both on the form's and the field's level in `TanStack/form` (`form.options.defaultValues`, `field.options.defaultValue`), so you can write your own `isDefaultValue()` helper if you need to emulate RHF's behavior.`
97β
98β
99## Field API
100β
101The Field API is an object passed to the render prop function when creating a field. It provides methods for working with the field's state.
102β
103Example:
104β
105```tsx
106<input
107 value={field.state.value}
108 onBlur={field.handleBlur}
109 onChange={(e) => field.handleChange(e.target.value)}
110/>
111```
112β
113## Validation
114β
115`@tanstack/react-form` provides both synchronous and asynchronous validation out of the box. Validation functions can be passed to the `form.Field` component using the `validators` prop.
116β
117Example:
118β
119```tsx
120<form.Field
121 name="firstName"
122 validators={{
123 onChange: ({ value }) =>
124 !value
125 ? 'A first name is required'
126 : value.length < 3
127 ? 'First name must be at least 3 characters'
128 : undefined,
129 onChangeAsync: async ({ value }) => {
130 await new Promise((resolve) => setTimeout(resolve, 1000))
131 return value.includes('error') && 'No "error" allowed in first name'
132 },
133 }}
134 children={(field) => (
135 <>
136 <input
137 value={field.state.value}
138 onBlur={field.handleBlur}
139 onChange={(e) => field.handleChange(e.target.value)}
140 />
141 <FieldInfo field={field} />
142 </>
143 )}
144/>
145```
146β
147## Validation Adapters
148β
149In addition to hand-rolled validation options, we also provide adapters like `@tanstack/zod-form-adapter`, `@tanstack/yup-form-adapter`, and `@tanstack/valibot-form-adapter` to enable usage with common schema validation tools like [Zod](https://zod.dev/), [Yup](https://github.com/jquense/yup), and [Valibot](https://valibot.dev/).
150β
151Example:
152β
153```tsx
154import { zodValidator } from '@tanstack/zod-form-adapter'
155import { z } from 'zod'
156β
157// ...
158<form.Field
159 name="firstName"
160 validatorAdapter={zodValidator()}
161 validators={{
162 onChange: z.string().min(3, 'First name must be at least 3 characters'),
163 onChangeAsyncDebounceMs: 500,
164 onChangeAsync: z.string().refine(
165 async (value) => {
166 await new Promise((resolve) => setTimeout(resolve, 1000))
167 return !value.includes('error')
168 },
169 {
170 message: "No 'error' allowed in first name",
171 },
172 ),
173 }}
174/>
175```
176β
177## Reactivity
178β
179`@tanstack/react-form` offers various ways to subscribe to form and field state changes, most notably the `form.useStore` hook and the `form.Subscribe` component. These methods allow you to optimize your form's rendering performance by only updating components when necessary.
180β
181Example:
182β
183```tsx
184const firstName = form.useStore((state) => state.values.firstName)
185//...
186<form.Subscribe
187 selector={(state) => [state.canSubmit, state.isSubmitting]}
188 children={([canSubmit, isSubmitting]) => (
189 <button type="submit" disabled={!canSubmit}>
190 {isSubmitting ? '...' : 'Submit'}
191 </button>
192 )}
193/>
194```
195β
196Note: The usage of the `form.useField` hook to achieve reactivity is discouraged since it is designed to be used thoughtfully within the `form.Field` component. You might want to use `form.useStore` instead.
197β
198## Array Fields
199β
200Array fields allow you to manage a list of values within a form, such as a list of hobbies. You can create an array field using the `form.Field` component with the `mode="array"` prop.
201β
202When working with array fields, you can use the fields `pushValue`, `removeValue`, `swapValues` and `moveValue` methods to add, remove, and swap values in the array.
203β
204Example:
205β
206```tsx
207<form.Field
208 name="hobbies"
209 mode="array"
210 children={(hobbiesField) => (
211 <div>
212 Hobbies
213 <div>
214 {!hobbiesField.state.value.length
215 ? 'No hobbies found.'
216 : hobbiesField.state.value.map((_, i) => (
217 <div key={i}>
218 <form.Field
219 name={`hobbies[${i}].name`}
220 children={(field) => {
221 return (
222 <div>
223 <label htmlFor={field.name}>Name:</label>
224 <input
225 id={field.name}
226 name={field.name}
227 value={field.state.value}
228 onBlur={field.handleBlur}
229 onChange={(e) => field.handleChange(e.target.value)}
230 />
231 <button
232 type="button"
233 onClick={() => hobbiesField.removeValue(i)}
234 >
235 X
236 </button>
237 <FieldInfo field={field} />
238 </div>
239 )
240 }}
241 />
242 <form.Field
243 name={`hobbies[${i}].description`}
244 children={(field) => {
245 return (
246 <div>
247 <label htmlFor={field.name}>Description:</label>
248 <input
249 id={field.name}
250 name={field.name}
251 value={field.state.value}
252 onBlur={field.handleBlur}
253 onChange={(e) => field.handleChange(e.target.value)}
254 />
255 <FieldInfo field={field} />
256 </div>
257 )
258 }}
259 />
260 </div>
261 ))}
262 </div>
263 <button
264 type="button"
265 onClick={() =>
266 hobbiesField.pushValue({
267 name: '',
268 description: '',
269 yearsOfExperience: 0,
270 })
271 }
272 >
273 Add hobby
274 </button>
275 </div>
276 )}
277/>
278```
279β
280These are the basic concepts and terminology used in the `@tanstack/react-form` library. Understanding these concepts will help you work more effectively with the library and create complex forms with ease.