@rsc-kit/mcp 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/recipes.js +37 -20
  2. package/dist/recipes.js.map +1 -1
  3. package/guides/admin-plugins.md +206 -6
  4. package/guides/api-routes.md +159 -215
  5. package/guides/authorization.md +103 -114
  6. package/guides/backend-answered-pages.md +301 -250
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +307 -174
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +5 -5
  12. package/guides/commands.md +251 -200
  13. package/guides/connection.md +50 -54
  14. package/guides/content-security-policy.md +133 -84
  15. package/guides/domains.md +190 -149
  16. package/guides/edge-caching.md +242 -268
  17. package/guides/emails.md +96 -45
  18. package/guides/errors.md +116 -137
  19. package/guides/feature-flags.md +100 -30
  20. package/guides/file-uploads.md +101 -26
  21. package/guides/fonts.md +139 -110
  22. package/guides/forms.md +520 -538
  23. package/guides/images.md +87 -28
  24. package/guides/index.json +13 -33
  25. package/guides/instrumentation.md +134 -95
  26. package/guides/isr.md +3 -3
  27. package/guides/live-data-in-production.md +695 -0
  28. package/guides/live-data.md +170 -839
  29. package/guides/mcp.md +83 -59
  30. package/guides/metadata.md +124 -179
  31. package/guides/navigation.md +118 -147
  32. package/guides/no-javascript.md +49 -57
  33. package/guides/offline.md +118 -153
  34. package/guides/openapi.md +100 -35
  35. package/guides/pages.md +160 -50
  36. package/guides/ppr.md +178 -256
  37. package/guides/pwa.md +251 -218
  38. package/guides/queries.md +171 -300
  39. package/guides/react-compiler.md +90 -50
  40. package/guides/redirects.md +141 -177
  41. package/guides/response-headers.md +76 -74
  42. package/guides/route-interception.md +112 -111
  43. package/guides/routing.md +216 -322
  44. package/guides/sections.md +63 -66
  45. package/guides/seo-files.md +127 -65
  46. package/guides/server-actions.md +285 -357
  47. package/guides/static-generation.md +131 -199
  48. package/guides/testing.md +272 -150
  49. package/guides/third-party-scripts.md +94 -47
  50. package/guides/typed-routes.md +115 -113
  51. package/guides/url-validation.md +113 -61
  52. package/guides/validation.md +53 -62
  53. package/guides/view-transitions.md +159 -132
  54. package/guides/where-it-runs.md +226 -162
  55. package/package.json +2 -2
  56. package/guides/admin.md +0 -520
  57. package/guides/deployment.md +0 -598
  58. package/guides/go.md +0 -538
  59. package/guides/laravel.md +0 -786
  60. package/guides/your-own-backend.md +0 -587
package/guides/forms.md CHANGED
@@ -2,29 +2,35 @@
2
2
 
3
3
  > Progressive forms, pending state and validation errors.
4
4
 
5
- `<Form>` submits to a server action: a component
6
- that handles the state for you, and a hook for when you want to hold it
7
- yourself. Both cover validation errors, pending state, optimistic updates and
8
- GET-form navigation.
5
+ `<Form>` submits to a server action and handles the state around it: pending,
6
+ validation errors, success and optimistic updates. It works before the page's
7
+ JavaScript has loaded.
9
8
 
10
- ## The rule: uncontrolled, unless one field needs otherwise
9
+ ```tsx title="NewOrder.tsx"
10
+ "use client";
11
11
 
12
- A form here is **uncontrolled by default**. Inputs keep their own value in
13
- the DOM, an initial value is React's `defaultValue`, and the action reads
14
- `FormData` on submit. No `useState` per field, no `value`/`onChange` pair,
15
- no re-render of the whole form on every keystroke — and after a refused
16
- submit the values are still there, because nothing re-rendered the inputs.
12
+ import { Form } from "@rsc-kit/core/form";
13
+ import * as orders from "../server-actions/orders";
17
14
 
18
- Reach for a controlled field only where the UI has to react *as* the user
19
- types — a character count, a live preview, a dependent select — and bind
20
- that one field with `useField` (below), which scopes the re-render to it.
21
- Coming from react-hook-form this is the same default; coming from TanStack
22
- Form or from `useState`-per-input it is the opposite, and the difference is
23
- most of why these forms stay fast.
15
+ export function NewOrder() {
16
+ return (
17
+ <Form action={orders.create}>
18
+ {({ pending, error }) => (
19
+ <>
20
+ <input name="title" />
21
+ {error('title') && <p>{error('title')}</p>}
22
+ <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
23
+ </>
24
+ )}
25
+ </Form>
26
+ );
27
+ }
28
+ ```
24
29
 
25
- ## The `<Form>` component
30
+ ## Submitting a form
26
31
 
27
- The simplest way to handle forms. Works without any hooks — just pass a server action and use the render-prop for pending state and errors.
32
+ Pass a server action as `action`. The children are a function that receives the
33
+ form's state:
28
34
 
29
35
  ```tsx title="TodoForm.tsx"
30
36
  "use client";
@@ -41,9 +47,7 @@ export default function TodoForm() {
41
47
  <>
42
48
  <input name="title" placeholder="What needs to be done?" />
43
49
  {error('title') && <span className="text-red-500">{error('title')}</span>}
44
- <button disabled={pending}>
45
- {pending ? 'Adding...' : 'Add Todo'}
46
- </button>
50
+ <button disabled={pending}>{pending ? 'Adding...' : 'Add Todo'}</button>
47
51
  </>
48
52
  )}
49
53
  </Form>
@@ -51,50 +55,50 @@ export default function TodoForm() {
51
55
  }
52
56
  ```
53
57
 
54
- The generic type parameter `<FormValues>` gives you autocomplete on `error()` and typed form data throughout the component.
55
-
56
- ### Two words: `error` and `field`
57
-
58
- There is one way to read a form, and it is the same everywhere — in the render
59
- prop, in a component of its own, with shadcn or without:
60
-
61
- - **`error('title')`** — the field's message, or `undefined`. Show it, or test
62
- it: `!!error('title')` is "invalid". Nested fields are paths:
63
- `error('address.city')`, `error('items[0].name')`. When the action says what
64
- it takes, the names are checked: `error('titel')` fails the typecheck instead
65
- of showing nothing, ever. See [Field names](#field-names).
66
- - **`formError`** — the refusal that is not about a field: the action's
67
- `serverError`, such as a payment required or a slot just taken, or a
68
- validation message for the whole form. `{formError && <p role="alert">{formError}</p>}`.
69
- It clears with the field errors. A failure thrown on the way, such as the
70
- network, still goes to `onError`.
71
- - **`field('title')`** — a binding to spread onto a control, for the few fields
72
- whose value this component has to hold. Most fields need nothing: they are
73
- uncontrolled, the DOM holds the value, and it is read back on submit.
74
-
75
- Beside them: `pending`, `dirty`, `succeeded`, `recentlySucceeded`, `reset()` and
76
- `clearErrors()`. A field is checked when it is left and when the form is
77
- submitted, so `error()` never lights up on a field nobody has reached.
78
-
79
- ### Props
80
-
81
- ```text
82
- action — server action function (POST) or URL string (GET)
83
- method — "get" | "post" (defaults to "post" for functions, "get" for strings)
84
- resetOnSuccess — auto-reset form on success (default: true)
85
- optimistic — callback for optimistic updates, called inside the transition
86
- onSuccess — called with the action result on success
87
- onError — called with validation errors on 422
88
- onSubmit — called before submit, return false to cancel
89
- prefetch — "hover" (default) | "mount" | "none" (GET forms only)
90
- replace — replace history state (GET forms)
91
- preserveScroll — keep scroll position (GET forms)
92
- ```
58
+ The inputs are ordinary named inputs. They keep their own value, and the action
59
+ reads them as `FormData` on submit. There's no `useState` per field and no
60
+ `value`/`onChange` pair, and typing doesn't re-render the form. Bind a field
61
+ only when the page has to react as it's typed: see
62
+ [controlling one field](#controlling-one-field).
63
+
64
+ The type parameter, `<FormValues>`, types the names `error()` accepts. With a
65
+ generated action you don't need it: the names come from the action.
66
+
67
+ What the render function receives:
68
+
69
+ | Name | What it is |
70
+ | --- | --- |
71
+ | `error(name)` | The field's message, or `undefined`. |
72
+ | `formError` | A refusal that isn't about one field. |
73
+ | `field(name)` | A binding to spread onto a control you need to hold. |
74
+ | `pending` | `true` while the submit is running. |
75
+ | `dirty` | Whether any value differs from what the form started with. |
76
+ | `succeeded`, `recentlySucceeded` | Whether the last submit succeeded; the second for two seconds only. |
77
+ | `reset()`, `clearErrors()` | Go back to the starting values; clear the errors. |
78
+ | `validate()`, `validating`, `valid(name)` | Ask the server to check fields now. |
79
+
80
+ ### Form props
81
+
82
+ | Prop | What it does |
83
+ | --- | --- |
84
+ | `action` | A server action (POST), or a URL (GET). |
85
+ | `method` | `"get"` or `"post"`. Defaults to `"post"` for an action and `"get"` for a URL. |
86
+ | `schema` | A schema to check the values with in the browser. |
87
+ | `defaultValues` | Starting values for bound fields. |
88
+ | `fields` | Field names, for a form whose values aren't posted fields. |
89
+ | `resetOnSuccess` | Reset the form after a successful submit. Default `true`. |
90
+ | `optimistic` | Called inside the transition, for [optimistic updates](#optimistic-updates). |
91
+ | `onSuccess` | Called with the action's result. |
92
+ | `onError` | Called with the validation errors on a 422. |
93
+ | `onSubmit` | Called before submitting. Return `false` to cancel. |
94
+ | `prefetch` | `"hover"` (default), `"mount"` or `"none"`. GET forms only. |
95
+ | `replace` | Replace the history entry. GET forms only. |
96
+ | `preserveScroll` | Keep the scroll position. GET forms only. |
93
97
 
94
98
  ### In a component of its own
95
99
 
96
- `useForm()` returns exactly what the render prop gets, so a piece of a form
97
- moved into its own component is written the same way it was inline:
100
+ `useForm()` returns what the render function receives, so part of a form can
101
+ move into its own component:
98
102
 
99
103
  ```tsx title="SubmitButton.tsx"
100
104
  "use client";
@@ -112,109 +116,36 @@ export function SubmitButton() {
112
116
  }
113
117
  ```
114
118
 
115
- Not React's `useFormStatus`: that is a different hook with a different answer,
116
- which is why this one is not called that.
117
-
118
- ---
119
-
120
- ### Field names
121
-
122
- `error()` and `clearErrors()` are typed from the action's input, so a typo
123
- fails `tsc` rather than silently never matching:
124
-
125
- ```tsx
126
- <Form action={ordersCreate}>
127
- {({ error }) => (
128
- <>
129
- {error('name')} {/* ok */}
130
- {error('address.city')} {/* ok: a nested path */}
131
- {error('items.0.sku')} {/* ok: a list's index */}
132
- {error('nmae')} {/* type error */}
133
- </>
134
- )}
135
- </Form>
136
- ```
137
-
138
- Where the names come from: a generated stub's typed parameter (the backend
139
- already lists the fields of the struct or the FormRequest-shaped array it takes
140
- in `rsc-host.json`, so nothing is written for this), or `createActionClient()`'s
141
- `.input(schema)`. Fields the form declares in `defaultValues` count too. When
142
- the action says nothing — a function of a `FormData`, a url, a cast — nothing is
143
- claimed and any name is accepted, as before. A name the backend reports that its
144
- input does not have, such as a key it computes, is a type error you can answer by
145
- declaring it in `defaultValues`.
146
-
147
- **A wrapper you write around a stub** says nothing on its own: a function of a
148
- `FormData` could read anything. Declare the fields on its parameter, where the
149
- code that reads them lives:
150
-
151
- ```tsx
152
- import type { FormFields } from '@rsc-kit/core/form'
153
-
154
- export async function renameApp(form: FormFields<'id' | 'name'>) {
155
- 'use server'
156
- await appsRename(String(form.get('id')), String(form.get('name')))
157
- }
158
- ```
159
-
160
- `<Form action={renameApp}>` then closes `error()` to `id` and `name` — and to
161
- whatever `defaultValues` adds. A `FormFields` is a `FormData`; nothing runs, and
162
- the names are a claim the types keep, not a check the browser makes. It names
163
- what `error()` may be asked for, so a field the backend refuses under that the
164
- form does not post — `redirect`, say — belongs in the same list.
165
-
166
- **A team-scoped action**, `func(ctx, team string, in NewApp)`, is a form's action
167
- once the team is bound. A form fills the struct parameter, the one after
168
- whatever you bound, and the generated stub keeps its field names:
169
-
170
- ```tsx
171
- const create = appsCreate.bind(null, team) // once, not inline
172
-
173
- <Form action={create}>{({ error }) => error('name')}</Form>
174
- ```
175
-
176
- Bind into a `const` first. Written inline in the JSX, TypeScript reads `bind`'s
177
- result before the form's render function is known and the names are not
178
- carried: the form still compiles, and is open as it always was. A stub whose
179
- parameters are all plain strings has no struct for a form to fill — wrap it, as
180
- above.
181
-
182
- **A form that posts nothing** — its values live in React state, or it is a
183
- button — has no `FormData` to name the fields on. Name them on the form:
184
-
185
- ```tsx
186
- <Form action={resize} fields={['size', 'copies']}>
187
- {({ error }) => error('size')} {/* error('sise') fails the typecheck */}
188
- </Form>
189
- ```
119
+ This isn't React's `useFormStatus`, which is a different hook with a different
120
+ answer.
190
121
 
191
- `fields` closes the set beside the action's own names — a bound stub's included —
192
- and `defaultValues`. It is types only: nothing is checked in the browser. It is
193
- also how to name a field the backend refuses under that the struct does not
194
- spell the same way, such as an untagged Go field `Host` that the backend reports
195
- as `host`; tagging the struct (`json:"host"`) is the cleaner fix.
122
+ ## Validation errors
196
123
 
197
- A component below the form types its own prop with `FieldNamesOf`:
124
+ When a submit fails validation, `error('title')` returns the field's message.
125
+ There's no `try`/`catch` to write and no state to hold.
198
126
 
199
127
  ```tsx
200
- import type { FieldNamesOf } from '@rsc-kit/core/form'
201
-
202
- type Props = { name: FieldNamesOf<typeof ordersCreate> }
128
+ {error('title') && <p>{error('title')}</p>}
129
+ {error('address.city')} {/* a nested field */}
130
+ {error('items[0].name')} {/* a field in a list */}
131
+ {formError && <p role="alert">{formError}</p>}
203
132
  ```
204
133
 
205
- ## Validation errors
134
+ - **`error(name)`** shows a field's message. `!!error('title')` tells you
135
+ whether the field is invalid.
136
+ - **`formError`** is a refusal that isn't about one field: the action's
137
+ `serverError`, such as a payment required or a slot just taken, or a message
138
+ for the whole form. It clears with the field errors.
139
+ - A failure on the way, such as the network, goes to `onError` instead.
206
140
 
207
- When a submit fails validation, `error('title')` answers with the field's
208
- message — there is no `try`/`catch` to write, and no state to hold.
141
+ Errors come from the schema in the browser and from the server, and `error()`
142
+ shows both. Where the server's come from depends on your backend: see
143
+ [Validation](/guides/validation).
209
144
 
210
- Where those errors come from depends on the host, and the components do not
211
- care. See [Validation](/guides/validation).
145
+ ### Returning an error from an action
212
146
 
213
- An action can also name a field itself, for a refusal no schema could know
214
- about. Through the [action client](/guides/server-actions#failing-on-something-a-schema-cannot-know)
215
- `fieldErrors` arrives with the handler's arguments, typed to its input. A plain
216
- `"use server"` function has no input type to draw on, so it imports the same
217
- thing untyped:
147
+ An action can refuse a field itself, for something no schema could know.
148
+ Return `fieldErrors()`:
218
149
 
219
150
  ```ts
220
151
  'use server';
@@ -230,217 +161,117 @@ export async function addTodo(formData: FormData) {
230
161
  }
231
162
  ```
232
163
 
233
- Either way, write `return fieldErrors(…)`. The form renders it under the field
234
- you named, exactly as it would a schema failure.
164
+ The form shows it under that field, the same as a schema failure. Through the
165
+ [action client](/guides/server-actions#failing-on-something-a-schema-cannot-know),
166
+ `fieldErrors` arrives with the handler's arguments, typed to its input.
235
167
 
236
- ---
168
+ ## Field names
237
169
 
238
- ## Optimistic updates
170
+ `error()` and `clearErrors()` are typed from the action's input, so a typo fails
171
+ the typecheck instead of never matching:
239
172
 
240
- Optimistic updates go through React's `useOptimistic`. The callback runs inside the transition, so React reverts it automatically on error.
241
-
242
- ```tsx title="TodoList.tsx"
243
- "use client";
244
-
245
- import { useOptimistic } from "react";
246
- import { Form } from "@rsc-kit/core/form";
247
- import { addTodo } from "./actions";
248
-
249
- type Todo = { id: number; title: string; done: boolean };
250
-
251
- export default function TodoList({ todos }: { todos: Todo[] }) {
252
- const [optimisticTodos, addOptimistic] = useOptimistic(
253
- todos,
254
- (state, newTodo: Todo) => [...state, newTodo]
255
- );
173
+ ```tsx
174
+ <Form action={orders.create}>
175
+ {({ error }) => (
176
+ <>
177
+ {error('name')} {/* ok */}
178
+ {error('address.city')} {/* ok: a nested path */}
179
+ {error('items.0.sku')} {/* ok: a list's index */}
180
+ {error('nmae')} {/* type error */}
181
+ </>
182
+ )}
183
+ </Form>
184
+ ```
256
185
 
257
- return (
258
- <div>
259
- <ul>
260
- {optimisticTodos.map((todo) => (
261
- <li key={todo.id}>{todo.title}</li>
262
- ))}
263
- </ul>
186
+ The names come from:
264
187
 
265
- <Form
266
- action={addTodo}
267
- optimistic={(data) =>
268
- addOptimistic({ id: Date.now(), title: data.title as string, done: false })
269
- }
270
- >
271
- <input name="title" />
272
- <button>Add</button>
273
- </Form>
274
- </div>
275
- );
276
- }
277
- ```
188
+ - a generated action's parameter. The backend lists the fields of the struct or
189
+ form request it takes in `rsc-host.json`, so you write nothing.
190
+ - `createActionClient()`'s `.input(schema)`.
191
+ - `defaultValues` on the form.
278
192
 
279
- ## Search and filter forms
193
+ When the action says nothing about its input - a function of `FormData`, a URL,
194
+ a cast - any name is accepted. A name the backend reports that its input
195
+ doesn't have, such as a key it computes, is a type error: add it to
196
+ `defaultValues`.
280
197
 
281
- When `action` is a URL string, the form navigates via RSC instead of doing a full page reload. Form fields are serialized as query parameters. Supports prefetching for instant navigation.
198
+ ### Typing a wrapper around an action
282
199
 
283
- ```tsx title="SearchForm.tsx"
284
- "use client";
200
+ A function of `FormData` could read anything, so it names no fields. Declare
201
+ them on its parameter with `FormFields`:
285
202
 
286
- import { Form } from "@rsc-kit/core/form";
203
+ ```tsx
204
+ import type { FormFields } from '@rsc-kit/core/form'
205
+ import * as apps from './server-actions/apps'
287
206
 
288
- export default function SearchForm() {
289
- return (
290
- <Form action="/search" method="get" prefetch="hover">
291
- <input name="q" placeholder="Search..." />
292
- <select name="sort">
293
- <option value="relevance">Relevance</option>
294
- <option value="date">Date</option>
295
- </select>
296
- <button>Search</button>
297
- </Form>
298
- );
207
+ export async function renameApp(form: FormFields<'id' | 'name'>) {
208
+ 'use server'
209
+ await apps.rename(String(form.get('id')), String(form.get('name')))
299
210
  }
300
211
  ```
301
212
 
302
- This navigates to `/search?q=hello&sort=date` via SPA navigation. The nearest Suspense boundary streams in the results. With `prefetch="hover"`, hovering the submit button pre-warms the base URL for instant feedback.
303
-
304
- ### A search on the page it is on
305
-
306
- When the form's `action` is the page the visitor is already on, there is no other page whose shell could stand in while the query runs: the shell would be this page with nothing in it. So the form does not show one. The page stays on screen, results and all, and the new results replace the old ones when they arrive. The input keeps what was typed, a Suspense boundary that was already showing its content keeps showing it instead of falling back to its skeleton, and Back returns to the query the visitor left.
213
+ `<Form action={renameApp}>` then accepts `error('id')` and `error('name')`, plus
214
+ whatever `defaultValues` adds. A `FormFields` is a `FormData`: the names are
215
+ types only, and nothing is checked in the browser. Include a field the backend
216
+ may refuse that the form doesn't post, such as `redirect`.
307
217
 
308
- `pending` is true until the new results are on screen, so the button can say so:
218
+ ### Binding an argument first
309
219
 
310
- ```tsx title="Lookup.tsx"
311
- "use client";
312
-
313
- import { Form } from "@rsc-kit/core/form";
220
+ For an action like `func(ctx, team string, in NewApp)`, bind the team and the
221
+ form fills the struct after it. Bind into a `const` first:
314
222
 
315
- export default function Lookup() {
316
- return (
317
- <Form action="/lookup" method="get">
318
- {({ pending }) => (
319
- <>
320
- <input name="q" />
321
- <button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
322
- </>
323
- )}
324
- </Form>
325
- );
326
- }
327
- ```
328
-
329
- To show a skeleton where the results are instead of the old results, style them from the form's own `data-pending` attribute. The results stay outside the form, and nothing in the page is a client component for it:
223
+ ```tsx
224
+ const create = apps.create.bind(null, team) // once, not inline
330
225
 
331
- ```css
332
- #results-skeleton { display: none }
333
- section:has(form[data-pending]) #results { display: none }
334
- section:has(form[data-pending]) #results-skeleton { display: block }
226
+ <Form action={create}>{({ error }) => error('name')}</Form>
335
227
  ```
336
228
 
337
- Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another query is still a page of its own. The form does not prefetch the page it is on, because it is already on it.
229
+ Written inline in the JSX, TypeScript loses the names: the form compiles, but
230
+ accepts any name. An action whose parameters are all plain strings has no
231
+ struct for a form to fill, so wrap it as above.
338
232
 
339
- ## Using it with shadcn/ui
233
+ ### A form that posts nothing
340
234
 
341
- It works, and mostly by doing nothing. `<Form>` reads a native `FormData`, so
342
- any component that ends up rendering a real form control is already compatible:
235
+ When the values live in React state, or the form is a single button, name the
236
+ fields on the form:
343
237
 
344
238
  ```tsx
345
- <Form action={createPost} schema={schema}>
346
- {({ pending, error }) => (
347
- <>
348
- <Label htmlFor="title">Title</Label>
349
- <Input id="title" name="title" />
350
- {error('title') && <p className="text-destructive">{error('title')}</p>}
351
-
352
- <Select name="kind">
353
- <SelectTrigger><SelectValue /></SelectTrigger>
354
- <SelectContent>
355
- <SelectItem value="post">Post</SelectItem>
356
- </SelectContent>
357
- </Select>
358
-
359
- <Checkbox name="draft" />
360
-
361
- <Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
362
- </>
363
- )}
239
+ <Form action={resize} fields={['size', 'copies']}>
240
+ {({ error }) => error('size')} {/* error('sise') fails the typecheck */}
364
241
  </Form>
365
242
  ```
366
243
 
367
- `Input`, `Textarea`, `Button` and `Label` are styled native elements, so `name`
368
- does what it always does.
369
-
370
- **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work** — they are Radix
371
- underneath, and Radix renders a hidden native control whenever you give it a
372
- `name`, for exactly this. Omit the `name` and it is invisible to the form; that
373
- is the only thing to remember.
374
-
375
- :::caution[Not shadcn's own `<Form>`]
376
- shadcn's `<Form>`, `<FormField>` and `<FormControl>` are wrappers around
377
- [react-hook-form](https://react-hook-form.com), which is a different system for
378
- the same job — its own state, its own validation, its own submit. Use one or
379
- the other, not both.
380
-
381
- Ours gives you the field errors the *server* returned, which is the half a
382
- client-side library cannot do.
383
- :::
384
-
385
- ### shadcn's `Field` components
244
+ `fields` adds to the action's own names and `defaultValues`. It is types only.
245
+ It also names a field the backend reports under a different spelling, such as
246
+ an untagged Go field `Host` reported as `host`, though tagging the struct
247
+ (`json:"host"`) is the cleaner fix.
386
248
 
387
- The newer `Field`, `FieldLabel`, `FieldError` and `FieldGroup` are plain
388
- presentational components — they take props rather than reading a form
389
- library's context, which is what the older `<FormField>` did. So they work here
390
- directly:
249
+ A component below the form types its prop with `FieldNamesOf`:
391
250
 
392
251
  ```tsx
393
- <Form action={reportBug} schema={formSchema}>
394
- {({ pending, error }) => (
395
- <FieldGroup>
396
- <Field data-invalid={!!error('title')}>
397
- <FieldLabel htmlFor="title">Bug title</FieldLabel>
398
- <Input id="title" name="title" aria-invalid={!!error('title')} />
399
- <FieldDescription>Keep it short and specific.</FieldDescription>
400
- <FieldError>{error('title')}</FieldError>
401
- </Field>
252
+ import type { FieldNamesOf } from '@rsc-kit/core/form'
402
253
 
403
- <Button type="submit" disabled={pending}>
404
- {pending ? 'Sending…' : 'Submit'}
405
- </Button>
406
- </FieldGroup>
407
- )}
408
- </Form>
254
+ type Props = { name: FieldNamesOf<typeof orders.create> }
409
255
  ```
410
256
 
411
- `FieldError` renders its children, and renders nothing when there are none —
412
- so `error('title')` goes straight in. Everything else is the same markup you
413
- would write with any other form library.
257
+ ## Setting the values
414
258
 
415
- The difference is where the errors came from. With TanStack Form or
416
- react-hook-form those are the *client's* validation; here `error()` answers with
417
- the client's **and** whatever the server sent back, because a refused action
418
- returns its fields rather than throwing them away.
419
-
420
- ### Setting the values
421
-
422
- The fields are uncontrolled, so an initial value is `defaultValue` — React's
423
- own, nothing of ours:
259
+ An initial value is React's own `defaultValue`:
424
260
 
425
261
  ```tsx
426
262
  <Input id="title" name="title" defaultValue={post.title} />
427
263
  ```
428
264
 
429
- After a refused submit the values are still there, because the DOM kept them:
430
- nothing re-rendered the inputs, so nobody typed twice. That is the upside of
431
- not owning the value.
265
+ After a refused submit the values are still there, because nothing re-rendered
266
+ the inputs.
432
267
 
433
- The exception is a submit that happened **before hydration**, where the page
434
- genuinely reloads. Then the server renders the page again, and putting the
435
- values back is the server's job — return them from the action and render them
436
- as `defaultValue`.
268
+ The exception is a submit made before the page's JavaScript loaded, which
269
+ reloads the page. The server renders the page again, so return the values from
270
+ the action and render them as `defaultValue`.
437
271
 
438
- ### The schema is written for the shape it wants
272
+ ## How the values are read
439
273
 
440
- Every value in a `FormData` is a string or a file, and a control that is off
441
- is not there at all — a fact that used to leak into every schema as
442
- `z.coerce.number()` and a per-checkbox `.transform()`. It does not any more.
443
- The form is read *the way the schema means it*, on both sides:
274
+ Write the schema for the values you want, not for the strings a form posts:
444
275
 
445
276
  ```ts
446
277
  const settings = z.object({
@@ -459,29 +290,31 @@ const settings = z.object({
459
290
  })
460
291
  ```
461
292
 
462
- Nothing in that schema knows it will meet a form. A schema describes itself
463
- (Standard JSON Schema — Zod 4 and ArkType do; Valibot not yet, and its
464
- values arrive as strings), and the decoder coerces to it: an absent
465
- `boolean` is `false`, `"on"`/`"1"` is `true`; a numeric string for a
466
- `number` is the number, an empty one for an optional number is absent; an
467
- `array` given one value is a list of one and given nothing is empty; nested
468
- names nest (`fields[0][name]` and `fields[0].name` alike); a union takes the
469
- branch its discriminator names; a control left blank is absent for a field
470
- the schema does not require, whatever its type — `z.email().optional()`
471
- accepts the empty input, an optional union is not read as its first branch
472
- — and is `""` for one it requires, so `z.string().min(1)` can say so. A value the schema refuses is still refused as itself — `"many"` for a
473
- number is the error you expect.
474
-
475
- A leaf JSON Schema cannot describe — `z.date()`, a custom check — costs only
476
- that leaf, which arrives as posted; the fields beside it are still read the
477
- way the schema means. A schema that cannot describe itself at all is said
478
- once, in development, with the library's reason.
479
-
480
- `<Form>` validates that object in the browser and the action decodes the
481
- same object on the server, from one codec, so a form that passes here passes
482
- there. A value sent through `<Form transform>` is encoded the same way back
483
- — a boolean as `"1"`/`"0"`, a nested object as `key[prop]` — and decodes to
484
- what was given.
293
+ No `z.coerce.number()` and no `.transform()` per checkbox. The form is read the
294
+ way the schema describes it, in the browser and again in the action:
295
+
296
+ - A `boolean` that is absent is `false`. `"on"` or `"1"` is `true`.
297
+ - A numeric string for a `number` is the number. An empty one for an optional
298
+ number is absent.
299
+ - An `array` given one value is a list of one, and given nothing is empty.
300
+ - Nested names nest: `fields[0][name]` and `fields[0].name` alike.
301
+ - A union takes the branch its discriminator names.
302
+ - A blank control is absent for a field the schema doesn't require, so
303
+ `z.email().optional()` accepts an empty input. It is `""` for a field the
304
+ schema requires, so `z.string().min(1)` can refuse it.
305
+ - A value the schema refuses is refused as it was posted: `"many"` for a number
306
+ is the error you expect.
307
+
308
+ This needs a schema that describes itself (Standard JSON Schema). Zod 4 and
309
+ ArkType do. Valibot doesn't yet, and its values arrive as strings. A part the
310
+ JSON Schema can't describe, such as `z.date()` or a custom check, arrives as
311
+ posted, and the rest of the form is still read normally. A schema that can't
312
+ describe itself at all is reported once in development, with the library's
313
+ reason.
314
+
315
+ A value sent through `<Form transform>` is encoded the same way back, a boolean
316
+ as `"1"`/`"0"` and a nested object as `key[prop]`, and decodes to what was
317
+ given.
485
318
 
486
319
  ### Lists of values
487
320
 
@@ -493,17 +326,16 @@ A repeated name is an array:
493
326
  // → { tags: ['react', 'vite'] }
494
327
  ```
495
328
 
496
- With one ticked that is `'react'`, a string — which no `z.array()` will accept.
497
- So for anything that is a list by nature, end the name in `[]` and it is always
498
- an array:
329
+ With only one ticked, that is the string `'react'`, which `z.array()` refuses.
330
+ End the name in `[]` and it is always an array:
499
331
 
500
332
  ```tsx
501
333
  <Checkbox name="tags[]" value="react" />
502
334
  // → { tags: ['react'] }
503
335
  ```
504
336
 
505
- The brackets are dropped from the key, and it is the same spelling a value is
506
- serialised back into — so a list survives a round trip.
337
+ The brackets are dropped from the key, and a value is written back the same
338
+ way, so a list survives a round trip.
507
339
 
508
340
  ### Nested and repeating groups
509
341
 
@@ -515,11 +347,10 @@ Names that describe a shape build it:
515
347
  <input name="items[0][name]" /> // the same field, other spelling
516
348
  ```
517
349
 
518
- Which is the shape your schema was written against — and the shape whose errors
519
- come back keyed the same way, because Standard Schema issue paths join with
520
- dots too. A refused `address.city` is `error('address.city')`.
350
+ Errors come back under the same paths: a refused `address.city` is
351
+ `error('address.city')`.
521
352
 
522
- Rows you add and remove are ordinary state; only the *names* have to line up:
353
+ Rows you add and remove are ordinary state. Only the names have to line up:
523
354
 
524
355
  ```tsx
525
356
  {rows.map((row, i) => (
@@ -527,85 +358,43 @@ Rows you add and remove are ordinary state; only the *names* have to line up:
527
358
  ))}
528
359
  ```
529
360
 
530
- ### Controlling one field
361
+ ## When fields are checked
531
362
 
532
- Most fields need nothing — the DOM holds the value and it is read back on
533
- submit. Two cases need more: a control with no native element behind it, and a
534
- value you want to show *as it is typed*.
363
+ **A field is checked when it is left, not as it is typed**, and when the form is
364
+ submitted. So `error()` has nothing for a field nobody has reached yet, and
365
+ there's no separate "touched" state to check.
535
366
 
536
- `field(name)` is for both. Spread it, the same way you would spread
537
- react-hook-form's `<Controller>` render props:
367
+ The form listens for `focusout` itself, so a plain `<Input name="title" />` is
368
+ covered without binding it.
538
369
 
539
- ```tsx
540
- <Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
541
- {({ field, error }) => (
542
- <Field data-invalid={!!error('description')}>
543
- <FieldLabel htmlFor="description">Description</FieldLabel>
370
+ ### Checking with the server before submit
544
371
 
545
- <InputGroup>
546
- <InputGroupTextarea id="description" {...field('description')} rows={6} />
547
- <InputGroupAddon align="block-end">
548
- <InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
549
- </InputGroupAddon>
550
- </InputGroup>
551
-
552
- <FieldError>{error('description')}</FieldError>
553
- </Field>
554
- )}
555
- </Form>
556
- ```
372
+ When a field is left **having changed**, the form asks the server to check it.
373
+ The action's guards and validation run for that field, and the action itself
374
+ doesn't. The answer shows on `error()` like any other. This catches what a
375
+ schema in the browser can't know, such as an email that is already subscribed
376
+ or a coupon that has expired.
557
377
 
558
- It gives you `{ name, value, onChange, onBlur }` — the same four things
559
- `<Controller>` does, for the same reason.
378
+ There's nothing to turn on. The actions that can be asked:
560
379
 
561
- `onChange` takes either a DOM event or a bare value, so a native input and a
562
- Radix `Select` both work without a wrapper. A bound field is still an ordinary
563
- named input, so it arrives in `FormData` with everything else: there is one
564
- source of truth, and nothing merges.
565
-
566
- Mix freely. Bind the one field that needs a character count and leave the rest
567
- alone.
568
-
569
- ### When a field is checked
570
-
571
- **A field is checked when it is left, not as it is typed.** An error that
572
- appears while someone is halfway through an email address is a form arguing
573
- with them; leaving the field is the moment they have finished saying what they
574
- meant. So `error()` has nothing for a field nobody has reached yet, and there is
575
- no separate "touched" to consult before showing it.
576
-
577
- It works on ordinary uncontrolled fields too — the form listens for `focusout`
578
- rather than each field listening for `blur`, so `<Input name="title" />` is
579
- covered without being bound to anything.
580
-
581
- ### Checked by the server before it is submitted
582
-
583
- A schema in the browser cannot know that an email is already subscribed, or
584
- that a coupon has expired. The server can, and `<Form>` asks it: when a field
585
- is left **having changed**, the form sends what it holds to the action marked
586
- as a check. The action's guards and validation run for that field; the action
587
- itself does not. Its answer lands on `error()` like any other.
588
-
589
- Nothing to opt into. Which actions can be asked:
590
-
591
- - a `createActionClient()` action with an input schema - its middleware and
592
- schema run, its handler is skipped;
593
- - a backend function the backend says it can check without running - in
594
- Laravel, any action whose first parameter is a form request (its
595
- `authorize()` and `rules()`, filtered to the field, as Laravel's
596
- Precognition does);
597
- - nothing else. A plain `"use server"` function cannot be stopped before its
380
+ - a `createActionClient()` action with an input schema. Its middleware and
381
+ schema run, and its handler is skipped.
382
+ - a backend function the backend can check without running it. In Laravel,
383
+ that is any action whose first parameter is a form request: its
384
+ `authorize()` and `rules()` run, filtered to the field, as Laravel's
385
+ Precognition does.
386
+ - nothing else. A plain `"use server"` function can't be stopped before its
598
387
  body, so it is never called to check, and the form stops asking after the
599
388
  first answer says so.
600
389
 
601
- A field the browser's schema already refuses costs no round trip, a field
602
- passed through without being changed is not asked about again, and a file goes
603
- only when its own field is the one being checked.
390
+ A field the browser's schema already refuses isn't sent. A field left without
391
+ being changed isn't asked about again. A file is sent only when its own field
392
+ is the one being checked.
604
393
 
605
394
  #### When a blur is not the moment
606
395
 
607
- `validate()` asks now, about the fields you name - or every field, with none.
608
- It resolves `true` when they pass. That is a wizard's step:
396
+ `validate()` asks now, about the fields you name, or every field with none. It
397
+ resolves `true` when they pass. Use it for a wizard's steps:
609
398
 
610
399
  ```tsx
611
400
  <Form action={register}>
@@ -631,19 +420,18 @@ It resolves `true` when they pass. That is a wizard's step:
631
420
  </Form>
632
421
  ```
633
422
 
634
- A step's fields stay in the form while hidden (render them with `hidden`
635
- rather than not at all), so the last step's submit sends every one.
636
-
637
- `*` stands for one segment of a nested name, as in Laravel: `validate('items.*.sku')`.
638
- For a field checked as it is typed, call `validate('handle')` from its
639
- `onChange` - and debounce it yourself; the form does not decide how often you
640
- may ask.
423
+ Keep each step's fields in the form while hidden (render them with `hidden`, not
424
+ conditionally), so the last step's submit sends every one.
641
425
 
642
- `validating` is true while a check is out. `valid(name)` is true once a check
643
- of that field passed and it has not been edited since - for a tick beside it,
644
- not for deciding anything.
426
+ - `*` stands for one segment of a nested name, as in Laravel:
427
+ `validate('items.*.sku')`.
428
+ - To check a field as it is typed, call `validate('handle')` from its
429
+ `onChange`, and debounce it yourself.
430
+ - `validating` is `true` while a check is out.
431
+ - `valid(name)` is `true` once a check of that field passed and it hasn't been
432
+ edited since. Use it for a tick beside the field, not for deciding anything.
645
433
 
646
- ### After a successful submit
434
+ ## After a successful submit
647
435
 
648
436
  ```tsx
649
437
  {({ succeeded, recentlySucceeded }) => (
@@ -651,12 +439,10 @@ not for deciding anything.
651
439
  )}
652
440
  ```
653
441
 
654
- `recentlySucceeded` is the same thing for two seconds — the tick that appears
655
- and fades. It is state rather than a timer in every form that wants one,
656
- because the timer has to be cleared when the component goes away and that is
657
- the part people forget.
442
+ `recentlySucceeded` is `succeeded` for two seconds only, for a tick that
443
+ appears and fades. The form clears the timer when the component goes away.
658
444
 
659
- ### Nothing to save yet
445
+ ## Disabling save until something changes
660
446
 
661
447
  ```tsx
662
448
  {({ dirty, reset }) => (
@@ -667,42 +453,49 @@ the part people forget.
667
453
  )}
668
454
  ```
669
455
 
670
- `dirty` is whether anything differs from what the form started with. It is
671
- read from the form itself — a snapshot of its `FormData` on mount, compared
672
- on every input — so an uncontrolled field counts, which is the reason it is
673
- the form's to answer and not something a component beside it could work
674
- out. A successful submit makes the current values the new baseline;
675
- `reset()` goes back to the first one. A bound control with no native
676
- element behind it counts too, through the store. Only a form that reads
677
- `dirty` is measured, and it renders once when the value first differs — not
678
- on the keystrokes after — so a field that subscribes for itself keeps its
679
- promise of rendering alone.
456
+ `dirty` is whether any value differs from what the form started with,
457
+ uncontrolled fields included. A successful submit makes the current values the
458
+ new starting point, and `reset()` goes back to the first one.
459
+
460
+ A form only measures `dirty` when something reads it, and it renders once when
461
+ the value first differs, not on every keystroke after.
462
+
463
+ ## Controlling one field
464
+
465
+ Bind a field with `field(name)` when it has no native element behind it, or
466
+ when you want to show its value as it's typed:
680
467
 
681
- ### Why not a `<Field>` component
468
+ ```tsx
469
+ <Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
470
+ {({ field, error }) => (
471
+ <Field data-invalid={!!error('description')}>
472
+ <FieldLabel htmlFor="description">Description</FieldLabel>
682
473
 
683
- TanStack Form and react-hook-form both hand you a field through a render prop —
684
- `<form.Field name="title" children={…}>`, `<Controller render={…}>`. It looks
685
- like the more capable design, and the reason they need it is worth being precise
686
- about, because the three of us are not in the same position.
474
+ <InputGroup>
475
+ <InputGroupTextarea id="description" {...field('description')} rows={6} />
476
+ <InputGroupAddon align="block-end">
477
+ <InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
478
+ </InputGroupAddon>
479
+ </InputGroup>
687
480
 
688
- **TanStack Form is controlled-first.** Every value lives in form state, so
689
- without per-field subscriptions one keystroke would re-render every field. The
690
- render prop is what scopes that, and the verbosity is the price of it.
481
+ <FieldError>{error('description')}</FieldError>
482
+ </Field>
483
+ )}
484
+ </Form>
485
+ ```
691
486
 
692
- **react-hook-form is uncontrolled-first**, like this. Its `register` is refs, not
693
- state, so typing re-renders nothing — and `<Controller>` is the opt-in for the
694
- fields that cannot work that way. The render prop there is doing something
695
- narrower: it scopes the re-render of a *controlled* field to that field alone.
487
+ `field()` returns `{ name, value, onChange, onBlur }`, like react-hook-form's
488
+ `<Controller>`. `onChange` takes a DOM event or a bare value, so a native input
489
+ and a Base UI or Radix `Select` both work without a wrapper. A bound field is
490
+ still a named input, so it is submitted with everything else.
696
491
 
697
- So the architecture here is react-hook-form's. The difference is what the
698
- controlled opt-in costs: `field()` is a function call rather than a render prop,
699
- which keeps the markup flat and means a bound field re-renders this component
700
- rather than only itself.
492
+ Bind only the fields that need it and leave the rest alone.
701
493
 
702
- That is the right trade for the number of controlled fields a form usually has —
703
- one or two, for a character count or a control with no native element.
494
+ ### In its own component
704
495
 
705
- When it is not, put the field in its own component and subscribe there:
496
+ `field()` re-renders the component holding the form. When a form is large, put
497
+ the field in its own component with `useField`, which re-renders that component
498
+ and nothing else:
706
499
 
707
500
  ```tsx
708
501
  import { useField } from '@rsc-kit/core/form'
@@ -714,19 +507,9 @@ function Title() {
714
507
  }
715
508
  ```
716
509
 
717
- The same two words, for one name: `field` to spread, `error` to show.
718
-
719
- `useField` re-renders **that component and nothing else** — not the form, not
720
- its siblings. Which is what `<Controller>` achieves with a render prop, except
721
- that the component you were going to write anyway is the boundary.
722
-
723
- So the scoping is there when a form is large enough to need it, and the flat
724
- markup is there when it is not.
725
-
726
- ### Reading the values from elsewhere
510
+ ### Reading a value from elsewhere
727
511
 
728
- A preview, a summary, a count — something that shows a value without being the
729
- field — reads it the same way the field does:
512
+ A preview, a summary or a count reads a value the same way:
730
513
 
731
514
  ```tsx
732
515
  function Preview() {
@@ -736,27 +519,12 @@ function Preview() {
736
519
  }
737
520
  ```
738
521
 
739
- Only a **bound** value can be read this way. An uncontrolled input's value
740
- belongs to the DOM, and nothing can know it changed without listening to it —
741
- bind the field with `field()` or `useField` and it can be read.
522
+ Only a bound field can be read this way. An uncontrolled input's value is in
523
+ the DOM, so bind it with `field()` or `useField` first.
742
524
 
743
- :::note[Inside the form, not outside it]
744
- `useForm()` and `useField()` read a context, so they work anywhere below `<Form>`. That is usually
745
- enough, because the `<form>` element can wrap as much of the page as you like,
746
- and a submit button outside it is `form="the-id"`.
747
-
748
- Worth knowing what the alternatives do here, because it is not as different as
749
- it looks. Reaching a form from another component is a context in all three:
750
- react-hook-form has `<FormProvider>` and `useFormContext()`, and TanStack Form
751
- has `createFormHookContexts()` with `useFormContext()` — which its own
752
- documentation calls a bridge for integration constraints, to be avoided when
753
- passing the form as a prop is possible. Ours needs no extra provider only
754
- because `<Form>` already is one.
755
-
756
- Where they are genuinely more flexible is *where the state is created*: their
757
- `useForm()` is called by you, so it can be hoisted as far up as you like. For
758
- the case where that matters — something that is not a descendant — create the
759
- store yourself and hand it to the form:
525
+ `useForm()` and `useField()` work anywhere below `<Form>`. A submit button
526
+ outside the `<form>` element can use `form="the-id"`. For a component that isn't
527
+ below the form at all, create the store yourself and pass it to both:
760
528
 
761
529
  ```tsx
762
530
  function Page() {
@@ -777,44 +545,258 @@ function TopBar({ store }) {
777
545
  }
778
546
  ```
779
547
 
780
- `useFormStore` is the values and nothing else — no submit, no errors, no
781
- optimistic updates. Creating it does not subscribe to it, so the component
782
- holding it does not re-render on every keystroke and take the whole subtree
783
- with it.
548
+ `useFormStore` holds the values only: no submit, no errors. Creating it doesn't
549
+ subscribe to it, so the component holding it doesn't re-render on every
550
+ keystroke.
551
+
552
+ ## Optimistic updates
553
+
554
+ Pass `optimistic` and update React's `useOptimistic` state in it. It runs
555
+ inside the transition, so React reverts it if the action fails:
556
+
557
+ ```tsx title="TodoList.tsx"
558
+ "use client";
559
+
560
+ import { useOptimistic } from "react";
561
+ import { Form } from "@rsc-kit/core/form";
562
+ import { addTodo } from "./actions";
563
+
564
+ type Todo = { id: number; title: string; done: boolean };
565
+
566
+ export default function TodoList({ todos }: { todos: Todo[] }) {
567
+ const [optimisticTodos, addOptimistic] = useOptimistic(
568
+ todos,
569
+ (state, newTodo: Todo) => [...state, newTodo]
570
+ );
571
+
572
+ return (
573
+ <div>
574
+ <ul>
575
+ {optimisticTodos.map((todo) => (
576
+ <li key={todo.id}>{todo.title}</li>
577
+ ))}
578
+ </ul>
579
+
580
+ <Form
581
+ action={addTodo}
582
+ optimistic={(data) =>
583
+ addOptimistic({ id: Date.now(), title: data.title as string, done: false })
584
+ }
585
+ >
586
+ <input name="title" />
587
+ <button>Add</button>
588
+ </Form>
589
+ </div>
590
+ );
591
+ }
592
+ ```
593
+
594
+ ## Stopping bots
595
+
596
+ Put `<Honeypot />` inside the form:
597
+
598
+ ```tsx
599
+ import { Form } from '@rsc-kit/core/form'
600
+ import { Honeypot } from '@rsc-kit/core/honeypot'
601
+
602
+ <Form action={subscribe}>
603
+ <input name="email" type="email" />
604
+ <Honeypot />
605
+ <button>Subscribe</button>
606
+ </Form>
607
+ ```
608
+
609
+ It renders a field people never see. It is off screen, out of the tab order,
610
+ hidden from screen readers and not autofilled. A bot that fills in every input
611
+ fills that one too. Its post is answered as though it worked and dropped before
612
+ the action runs, so the action never sees it and the bot learns nothing.
613
+
614
+ - It works in any form that posts to a server action: `<Form>`, a plain
615
+ `<form action={…}>`, with JavaScript or without, and for a `"use server"`
616
+ function or a Laravel or Go action. The check happens in the renderer,
617
+ before the call reaches the backend.
618
+ - The trap is taken out of the form either way, so the action sees only the
619
+ fields a person filled in.
620
+ - The field is named `homepage`. `<Honeypot name="website" />` picks another
621
+ name, if the form has a real field called `homepage`. Forms without
622
+ `<Honeypot />` are not checked, so a `homepage` field elsewhere is ordinary.
623
+
624
+ It stops the crudest spam, not a determined attacker. A form worth attacking
625
+ wants a rate limit on its action as well, such as Laravel's `throttle`
626
+ middleware on the action class. [Blueprints](/guides/blueprints/#stopping-bots)
627
+ show it, and [protecting a server action](/guides/authorization/#protect-a-server-action)
628
+ covers guarding one written in JavaScript.
629
+
630
+ ## Search and filter forms
631
+
632
+ When `action` is a URL, the form navigates to it with the fields as the query
633
+ string, without a full page reload:
634
+
635
+ ```tsx title="SearchForm.tsx"
636
+ "use client";
784
637
 
785
- `useField(name, store)` takes one explicitly; without one it reads the context,
786
- which is what almost every form wants.
638
+ import { Form } from "@rsc-kit/core/form";
639
+
640
+ export default function SearchForm() {
641
+ return (
642
+ <Form action="/search" method="get" prefetch="hover">
643
+ <input name="q" placeholder="Search..." />
644
+ <select name="sort">
645
+ <option value="relevance">Relevance</option>
646
+ <option value="date">Date</option>
647
+ </select>
648
+ <button>Search</button>
649
+ </Form>
650
+ );
651
+ }
652
+ ```
653
+
654
+ This goes to `/search?q=hello&sort=date`, and the nearest Suspense boundary
655
+ streams in the results. With `prefetch="hover"`, hovering the submit button
656
+ starts loading the page.
657
+
658
+ ### A search on the page it is on
659
+
660
+ When the form's `action` is the page the visitor is on, the page stays on
661
+ screen while the query runs, and the new results replace the old ones when
662
+ they arrive. The input keeps what was typed, a Suspense boundary already
663
+ showing content keeps showing it, and Back returns to the previous query.
664
+
665
+ `pending` stays `true` until the new results are on screen:
666
+
667
+ ```tsx title="Lookup.tsx"
668
+ "use client";
669
+
670
+ import { Form } from "@rsc-kit/core/form";
671
+
672
+ export default function Lookup() {
673
+ return (
674
+ <Form action="/lookup" method="get">
675
+ {({ pending }) => (
676
+ <>
677
+ <input name="q" />
678
+ <button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
679
+ </>
680
+ )}
681
+ </Form>
682
+ );
683
+ }
684
+ ```
685
+
686
+ To show a skeleton instead of the old results, style them from the form's
687
+ `data-pending` attribute. The results can stay outside the form, with no client
688
+ component for them:
689
+
690
+ ```css
691
+ #results-skeleton { display: none }
692
+ section:has(form[data-pending]) #results { display: none }
693
+ section:has(form[data-pending]) #results-skeleton { display: block }
694
+ ```
695
+
696
+ Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another
697
+ query loads it as a new page. The form doesn't prefetch the page it is already
698
+ on.
699
+
700
+ ## Using it with shadcn/ui
701
+
702
+ shadcn's inputs work as they are, because `<Form>` reads the form's native
703
+ `FormData`:
704
+
705
+ ```tsx
706
+ <Form action={createPost} schema={schema}>
707
+ {({ pending, error }) => (
708
+ <>
709
+ <Label htmlFor="title">Title</Label>
710
+ <Input id="title" name="title" />
711
+ {error('title') && <p className="text-destructive">{error('title')}</p>}
712
+
713
+ <Select name="kind">
714
+ <SelectTrigger><SelectValue /></SelectTrigger>
715
+ <SelectContent>
716
+ <SelectItem value="post">Post</SelectItem>
717
+ </SelectContent>
718
+ </Select>
719
+
720
+ <Checkbox name="draft" />
721
+
722
+ <Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
723
+ </>
724
+ )}
725
+ </Form>
726
+ ```
727
+
728
+ - `Input`, `Textarea`, `Button` and `Label` are styled native elements.
729
+ - **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work**, on Base UI or
730
+ Radix. Each renders a hidden native control when you give it a `name`. Without
731
+ a `name`, the form can't see it.
732
+ - A pick in a Base UI `Select` changes its hidden control without firing an
733
+ event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
734
+ the change.
735
+
736
+ :::caution[Not shadcn's own `<Form>`]
737
+ shadcn's `<Form>`, `<FormField>` and `<FormControl>` wrap
738
+ [react-hook-form](https://react-hook-form.com), which has its own state,
739
+ validation and submit. Use one or the other, not both.
787
740
  :::
788
741
 
742
+ ### shadcn's `Field` components
743
+
744
+ `Field`, `FieldLabel`, `FieldError` and `FieldGroup` take props rather than
745
+ reading a form library's context, so they work directly:
746
+
747
+ ```tsx
748
+ <Form action={reportBug} schema={formSchema}>
749
+ {({ pending, error }) => (
750
+ <FieldGroup>
751
+ <Field data-invalid={!!error('title')}>
752
+ <FieldLabel htmlFor="title">Bug title</FieldLabel>
753
+ <Input id="title" name="title" aria-invalid={!!error('title')} />
754
+ <FieldDescription>Keep it short and specific.</FieldDescription>
755
+ <FieldError>{error('title')}</FieldError>
756
+ </Field>
757
+
758
+ <Button type="submit" disabled={pending}>
759
+ {pending ? 'Sending…' : 'Submit'}
760
+ </Button>
761
+ </FieldGroup>
762
+ )}
763
+ </Form>
764
+ ```
765
+
766
+ `FieldError` renders nothing when it has no children, so `error('title')` goes
767
+ straight in. Unlike with a client-side form library, `error()` includes the
768
+ errors the server sent back.
769
+
789
770
  ## It works before hydration
790
771
 
791
- The action goes on the `<form>` element as well as into the submit handler, so
792
- the markup is submittable on its own. Someone who hits enter before the
793
- javascript arrives still reaches the server; the page reloads with the result
794
- instead of updating in place.
795
-
796
- What happens on the wire: React writes the action's id into the form as a
797
- hidden field and points the form at the page's own url, and the browser
798
- posts there. The host reads the fields, runs the action they name exactly as
799
- the enhanced path would have called it, and renders the page again with what
800
- it returned seated in the form that posted — so a refusal shows on its
801
- fields, `error('email')` included, for a visitor with no
802
- javascript at all. A `redirect()` the action throws is followed as a
803
- document's would be; a cookie it sets is on the answer. Same origin only, as
804
- an action is, and the answer is never stored. A stored page is the one most
805
- likely to be submitted this way — it paints before its runtime arrives —
806
- which is why this is not optional.
807
-
808
- The seating is React's own `useActionState`, which `<Form>` uses under a
809
- wrapper bound to your action: React hands a form-state action a
810
- `(previousState, formData)` pair, and your action keeps taking the
811
- `FormData` alone. A `useActionState` of your own works the same way, with
812
- an action written for the pair.
813
-
814
- The two do not fight. The handler calls `preventDefault()` first, and React does
815
- not run a form action for a submit that was cancelled — so the enhanced path
816
- wins whenever there is one, and the native path is what is left when there is
817
- not.
818
-
819
- Nothing to turn on. It is why the fields are real `name` attributes rather than
820
- controlled state: a browser can read them without help.
772
+ A form can be submitted before the page's JavaScript has loaded. The browser
773
+ posts it, and the page reloads with the result instead of updating in place.
774
+ There is nothing to turn on.
775
+
776
+ - The action runs as it would have otherwise, and a refusal shows on its
777
+ fields, `error('email')` included, for a visitor with no JavaScript at all.
778
+ - A `redirect()` from the action is followed, and a cookie it sets is kept.
779
+ - It is same origin only, as an action is, and the answer is never stored.
780
+
781
+ A stored page is the one most likely to be submitted this way, since it shows
782
+ before its JavaScript arrives. It is also why fields are real `name` attributes
783
+ rather than state: the browser can read them without help.
784
+
785
+ `<Form>` uses React's `useActionState` for this, and your action still takes
786
+ the `FormData` alone. A `useActionState` of your own works too, with an action
787
+ written for `(previousState, formData)`. Once the page has hydrated, the form
788
+ cancels the native submit and handles it itself.
789
+
790
+ ## Coming from react-hook-form or TanStack Form
791
+
792
+ The default is react-hook-form's: fields are uncontrolled, and typing
793
+ re-renders nothing. TanStack Form is controlled-first, so it is the opposite.
794
+
795
+ | | react-hook-form | Here |
796
+ | --- | --- | --- |
797
+ | A plain field | `register('title')` | `name="title"` |
798
+ | A controlled field | `<Controller render={…}>` | `field('title')` |
799
+ | A field that re-renders alone | `<Controller>` | `useField('title')` in its own component |
800
+ | Reaching the form from below | `useFormContext()` | `useForm()` |
801
+ | State created above the form | `useForm()` | `useFormStore()` |
802
+ | Errors from the server | written by hand | `error()`, with the browser's |