react-f0rm 1.1.1 → 1.3.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.
- package/README.md +242 -39
- package/dist/devtools/index.cjs.js +1 -1
- package/dist/devtools/index.cjs.js.map +1 -1
- package/dist/devtools/index.d.ts +2 -2
- package/dist/devtools/index.mjs +1 -1
- package/dist/devtools/index.mjs.map +1 -1
- package/dist/errors-BKrUdpfI.cjs.js +2 -0
- package/dist/errors-BKrUdpfI.cjs.js.map +1 -0
- package/dist/errors-CrQBddrJ.mjs +2 -0
- package/dist/errors-CrQBddrJ.mjs.map +1 -0
- package/dist/form-CeKSBs31.d.ts +486 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1097 -118
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1082 -544
- package/dist/index.umd.js.map +1 -1
- package/dist/index.umd.min.js +2 -2
- package/dist/index.umd.min.js.map +1 -1
- package/dist/persist.cjs.js +2 -0
- package/dist/persist.cjs.js.map +1 -0
- package/dist/persist.d.ts +49 -0
- package/dist/persist.mjs +2 -0
- package/dist/persist.mjs.map +1 -0
- package/dist/resolvers/standard-schema.cjs.js +1 -1
- package/dist/resolvers/standard-schema.cjs.js.map +1 -1
- package/dist/resolvers/standard-schema.d.ts +7 -5
- package/dist/resolvers/standard-schema.mjs +1 -1
- package/dist/resolvers/standard-schema.mjs.map +1 -1
- package/dist/resolvers/yup.cjs.js +1 -1
- package/dist/resolvers/yup.cjs.js.map +1 -1
- package/dist/resolvers/yup.d.ts +1 -1
- package/dist/resolvers/yup.mjs +1 -1
- package/dist/resolvers/yup.mjs.map +1 -1
- package/dist/resolvers/zod.cjs.js +1 -1
- package/dist/resolvers/zod.cjs.js.map +1 -1
- package/dist/resolvers/zod.d.ts +1 -1
- package/dist/resolvers/zod.mjs +1 -1
- package/dist/resolvers/zod.mjs.map +1 -1
- package/dist/server/index.cjs.js +2 -0
- package/dist/server/index.cjs.js.map +1 -0
- package/dist/server/index.d.ts +77 -0
- package/dist/server/index.mjs +2 -0
- package/dist/server/index.mjs.map +1 -0
- package/dist/validate-CNtuUhmk.mjs +2 -0
- package/dist/validate-CNtuUhmk.mjs.map +1 -0
- package/dist/validate-Cl4ksNFu.cjs.js +2 -0
- package/dist/validate-Cl4ksNFu.cjs.js.map +1 -0
- package/dist/validate-nksgv1pR.d.ts +272 -0
- package/dist/values-Cu6awQOJ.cjs.js +2 -0
- package/dist/values-Cu6awQOJ.cjs.js.map +1 -0
- package/dist/values-DRY-a32G.mjs +2 -0
- package/dist/values-DRY-a32G.mjs.map +1 -0
- package/package.json +87 -29
- package/dist/form-2_tBkEXU.mjs +0 -2
- package/dist/form-2_tBkEXU.mjs.map +0 -1
- package/dist/form-BiDaJLjD.d.ts +0 -826
- package/dist/form-BwLNQ6WB.cjs.js +0 -2
- package/dist/form-BwLNQ6WB.cjs.js.map +0 -1
- package/dist/validate-2XUilILy.d.ts +0 -22
package/README.md
CHANGED
|
@@ -11,14 +11,19 @@ Coming from TanStack Form? [Migrating from TanStack Form](./docs/from-tanstack-f
|
|
|
11
11
|
|
|
12
12
|
## Features
|
|
13
13
|
|
|
14
|
-
- **Field-level subscriptions.** Editing one field re-renders exactly that field's component, not the whole form. State is read through `useSyncExternalStore`, so snapshots stay consistent under concurrent rendering (no tearing).
|
|
15
|
-
- **
|
|
14
|
+
- **Field-level subscriptions.** Editing one field re-renders exactly that field's component, not the whole form. State is read through React's native `useSyncExternalStore`, so snapshots stay consistent under concurrent rendering (no tearing).
|
|
15
|
+
- **One shared runtime dependency.** The event core is `@for-fun/event-emitter` (a base library by the same author, ~2.3 KB gzip standalone) kept **external** in the ESM/CJS builds — an app that already depends on it dedupes the copy, and the emitted `Form.emitter` handle interops with the package's own `on()`/`emit()` types. `useSyncExternalStore` comes from React itself — the peer range is `react >=18`.
|
|
16
|
+
- **Truly type-safe paths.** `FieldPath<T>` enumerates every valid field name for your values shape and `PathValue<T, P>` resolves the value type at that path — typos in field names fail at compile time on the generic APIs (`useField`, `setValue`, `getValue`, `useValue`, …), values are inferred.
|
|
16
17
|
- **One schema adapter for every library.** The Standard Schema resolver covers zod (v3.24+/v4), valibot v1, arktype and any other Standard Schema v1 implementation through a single tree-shakeable entry point.
|
|
17
18
|
- **Headless, with accessibility hooks.** You own the markup. When you opt into error rendering via `renderError`, `aria-invalid` and `aria-describedby` are wired up automatically.
|
|
18
|
-
- **Tombstone unregister.** Unmounted fields drop out of `getValues()` instead of silently reviving their initial values on the next read.
|
|
19
|
-
- **
|
|
19
|
+
- **Tombstone unregister.** Unmounted fields drop out of `getValues()` instead of silently reviving their initial values on the next read; `createForm({shouldUnregister: false})` flips the form-wide default to RHF's keep-the-value semantics.
|
|
20
|
+
- **Async initial values.** `initialValues` accepts a Promise or a thunk returning one — the form starts empty with `isLoading: true` (`useIsLoading`, `useFormState().isLoading`) and lands the resolved values as the baseline, react-hook-form's async `defaultValues` shape.
|
|
21
|
+
- **Copy-on-write `getValues()`.** An ownership-tracked merge allocates each container once per read instead of re-copying whole branches for every key. The result shares references across reads, so treat it as read-only — `structuredClone` the tree when you need a mutable copy. In development the snapshot is deep-frozen: mutating it throws at the offending line instead of silently corrupting the shared cache (production builds share baseline references unchanged).
|
|
20
22
|
- **Multiple errors per field.** Each field stores an ordered `FieldError[]` — `getFieldErrors`/`useFieldErrors` read them all, and schema resolvers forward every issue instead of stopping at the first.
|
|
21
|
-
- **
|
|
23
|
+
- **Mount validation.** `createForm({validateOnMount: true})` (or per field) kicks every field's validator once after mount, so errors show on an untouched form; with an async `initialValues` source the kicks wait for the resolved baseline instead of validating the empty shell.
|
|
24
|
+
- **Form-level status channel.** `setStatus`/`useStatus` carry non-field state — server session flags, wizard steps, account-level errors — through the same event core (Formik's `status` role).
|
|
25
|
+
- **Async validation with cancellation.** `validateDebounce` per field — and on the form-level `validate` — plus an `AbortSignal` handed to every validator: a superseded round aborts its in-flight fetch, and pending debounce windows count as validating so submit waits them out. `asyncAlways` (field or form level) keeps a field's validator running even when its `required` gate failed, landing both verdicts per-source.
|
|
26
|
+
- **Declarative rules, native and store-side.** `rules` (`required`/`min`/`max`/`minLength`/`maxLength`/`pattern`/`validate` callbacks) compile into the store-based pipeline — queryable errors, your messages, `renderError`/`aria-invalid` — and the declarative subset renders as native constraint attributes (`required`, `minLength`, `pattern`, …) for `:invalid` styling and screen-reader hints. A user-passed attribute always wins over the derived one.
|
|
22
27
|
- **Precise lifecycle control.** `reset(form, values, {keepDirtyValues, …})` covers refetch-without-clobbering-dirty-drafts, `setFocus(form, name)` focuses programmatically, and `trigger(form, name?)` resolves `Promise<boolean>` once validation settles.
|
|
23
28
|
- **Typed, nestable form contexts.** `createFormContext<Values>()` gives each app area an isolated provider whose `useField`/`useFieldArray` take `FieldPath<Values>` names without hand-written generics.
|
|
24
29
|
- **SSR out of the box.** `renderToString` renders initial values and the server snapshot matches the client's first render, so hydration is consistent.
|
|
@@ -26,6 +31,8 @@ Coming from TanStack Form? [Migrating from TanStack Form](./docs/from-tanstack-f
|
|
|
26
31
|
|
|
27
32
|
## Install
|
|
28
33
|
|
|
34
|
+
Requires React 18 or newer (native `useSyncExternalStore`, no shim).
|
|
35
|
+
|
|
29
36
|
```sh
|
|
30
37
|
npm i react-f0rm
|
|
31
38
|
```
|
|
@@ -34,23 +41,28 @@ or
|
|
|
34
41
|
yarn add react-f0rm
|
|
35
42
|
```
|
|
36
43
|
|
|
44
|
+
Try the components without writing an app first: `npm run storybook` (this repo) serves the Storybook gallery — every bound component, rules, field arrays, devtools, and the uncontrolled mode are live-editable there. The [docs site](https://wmzy.github.io/react-f0rm/) carries the full guides (validation, sub-forms, server actions, UI-kit integration, migration from Formik/RHF/TanStack Form).
|
|
45
|
+
|
|
37
46
|
## Benchmarks
|
|
38
47
|
|
|
39
|
-
tinybench
|
|
48
|
+
tinybench, run on a desktop-class machine (AMD Ryzen 7 8745HS). Measured rme varies by run — the µs means wobble between runs and under load, so treat them as one significant figure (collected 2026-09: two render runs 130µs/138µs for f0rm vs 128µs/124µs for RHF `Controller` — the 100-field controlled row flip-flops inside noise).
|
|
40
49
|
|
|
41
50
|
| Scenario | react-f0rm | Baseline | Speedup |
|
|
42
51
|
|---|---|---|---|
|
|
43
|
-
| Change one of 100 controlled fields |
|
|
52
|
+
| Change one of 100 controlled fields | 138µs/change (~7,500 ops/s) | RHF `Controller`: 124µs (~8,200 ops/s) | parity (± noise; the row flips run to run) |
|
|
53
|
+
| Change one of 100 controlled fields | 138µs/change (~7,500 ops/s) | TanStack `form.Field`: 335µs (~3,000 ops/s) | ~2.4× |
|
|
44
54
|
| Components re-rendered per change | 1 of 100 `Field`s | — | — |
|
|
45
|
-
|
|
|
46
|
-
|
|
|
47
|
-
|
|
|
48
|
-
|
|
|
55
|
+
| Change one of 100 uncontrolled fields | 12.5µs/change (~80,700 ops/s) | RHF `register`: 11.7µs (~86,200 ops/s) | parity (~7% apart) |
|
|
56
|
+
| `getValues()`, 100 fields × depth 3 (cold compute; DEV snapshot guard on both paths) | 55.9µs (ownership merge) | legacy chained `set`: 95.9µs | 1.7× |
|
|
57
|
+
| Change one of 1000 controlled fields | 0.652ms/change (~1,550 ops/s) | RHF `Controller`: 1.22ms (~840 ops/s) | ~1.9× |
|
|
58
|
+
| Async validation storm — burst of 3 changes × 50 debounced async validators, settled via `trigger` | 21.4ms/burst (~47 ops/s) | — | — |
|
|
59
|
+
| `await trigger(form)` — 100 mixed validators (50 sync + 50 async) settle | 5.33ms (~196 ops/s) | — | — |
|
|
49
60
|
|
|
50
61
|
Notes:
|
|
51
62
|
|
|
52
|
-
-
|
|
53
|
-
-
|
|
63
|
+
- The uncontrolled row is the apples-to-apples `register` comparison: react-f0rm's `uncontrolled: true` (no value subscription) runs at RHF-`register` parity — 12.5µs vs 11.7µs per change — while keeping errors/touched/disabled/validating reactive, which raw `register` does not. The controlled comparison uses `Controller`, RHF's per-field-subscribed controlled counterpart, and `form.Field` is TanStack's same-model counterpart: field-level subscriptions, ~2.4× the change cost.
|
|
64
|
+
- Both `getValues()` paths pay the DEV snapshot guard (`freezeValues`: clone + freeze), so the comparison isolates the merge strategy; in production neither side pays it. Ownership merging also cut container allocations from 300 to 111.
|
|
65
|
+
- The 100-field controlled row is genuinely within noise of parity (two runs landed on opposite sides); the 1000-field row is the reliable separation — field-level subscriptions scale better than `Controller`'s per-change work.
|
|
54
66
|
|
|
55
67
|
Reproduce with:
|
|
56
68
|
|
|
@@ -65,27 +77,30 @@ react-f0rm vs the established options. react-f0rm figures come from this repo (s
|
|
|
65
77
|
|
|
66
78
|
| | react-f0rm | React Hook Form | TanStack Form | Formik |
|
|
67
79
|
|---|---|---|---|---|
|
|
68
|
-
| Rendering model | Controlled fields with field-level subscriptions (`useSyncExternalStore`): editing one of 100 fields re-renders exactly 1 component | Uncontrolled `register` by default (no React re-render while typing); `Controller` opts into per-field re-renders | Field-level subscriptions (`form.Field` / `useField`), each field re-renders itself | Form-wide context: any state change re-renders all subscribed components |
|
|
69
|
-
| Unregister on unmount | Unregisters by default — an unmounted field drops out of `getValues()` (tombstone) instead of silently reviving its initial value; `shouldUnregister: false` keeps it | Value kept by default (`shouldUnregister` defaults to `false`); opt in per field or form to unregister on unmount | Values live in the form store; unmounting a field's UI keeps its value and state | No unregister concept — values persist until `reset` |
|
|
80
|
+
| Rendering model | Controlled fields with field-level subscriptions (`useSyncExternalStore`): editing one of 100 fields re-renders exactly 1 component; `uncontrolled: true` drops the value subscription and runs at RHF-`register` parity (12.3µs vs 12.1µs bench) while errors/touched/disabled stay reactive | Uncontrolled `register` by default (no React re-render while typing); `Controller` opts into per-field re-renders | Field-level subscriptions (`form.Field` / `useField`), each field re-renders itself — the same model, 3.2× the per-change cost (355µs vs 111µs bench) | Form-wide context: any state change re-renders all subscribed components |
|
|
81
|
+
| Unregister on unmount | Unregisters by default — an unmounted field drops out of `getValues()` (tombstone) instead of silently reviving its initial value; `shouldUnregister: false` per field or per form (`createForm({shouldUnregister: false})`) keeps it | Value kept by default (`shouldUnregister` defaults to `false`); opt in per field or form to unregister on unmount | Values live in the form store; unmounting a field's UI keeps its value and state | No unregister concept — values persist until `reset` |
|
|
70
82
|
| Schema adapters | One Standard Schema entry point (`react-f0rm/resolvers/standard-schema`) covers zod, valibot, arktype, …; legacy zod/yup resolvers also shipped | `@hookform/resolvers` — one adapter module per validation library | Built-in `standardSchemaValidators` (Standard Schema v1), plus per-library adapter packages | Yup built in via `validationSchema`; other libraries hand-wired in `validate` |
|
|
71
|
-
| Path type safety | `FieldPath<T>` / `PathValue<T, P>`: every valid path enumerated, value type resolved, typos fail at compile time | `Path<T>` / `FieldPath` type-level path checking | Deep inference, including validator argument types — the strongest of the four | Top-level `keyof` only; nested paths are untyped strings |
|
|
72
|
-
| Async
|
|
83
|
+
| Path type safety | `FieldPath<T>` / `PathValue<T, P>`: every valid path enumerated, value type resolved, typos fail at compile time on the generic APIs (`useField`, `setValue`, `getValue`, …), and the `validate` value argument is path-inferred on `useField`/`Field` (`PathValueOf<T, P>`) | `Path<T>` / `FieldPath` type-level path checking | Deep inference, including validator argument types — the strongest of the four | Top-level `keyof` only; nested paths are untyped strings |
|
|
84
|
+
| Async initial values | `initialValues: T \| Promise<T> \| () => T \| Promise<T>`: async sources start the form empty with `isLoading: true` (`useIsLoading` / `useFormState().isLoading`) and land the resolved values as the baseline | Async `defaultValues` supported (`formState.isLoading`) | `defaultValues: () => Promise<T>` supported | Not built in — resolve before rendering, or re-render after fetch |
|
|
85
|
+
| Async validation | `validateDebounce` per field + `meta.signal` (`AbortSignal`) handed to every validator — superseded rounds cancel their in-flight work; pending debounce counts as validating so submit waits; `asyncAlways` keeps the validator running when the `required` gate failed, landing both verdicts per-source | Async validators supported, but no built-in debounce and no cancellation signal — both are hand-rolled per project | Built in: `asyncDebounceMs` debounces, the validator meta carries an `AbortSignal`, `asyncAlways` runs async validation even when sync validation failed | Async `validate` supported; no debounce, no signal |
|
|
86
|
+
| Mount validation | `validateOnMount` form-level (`createForm` / `<Form>`) or per field — fields with a validator kick once after mount; deferred until an async `initialValues` source lands, validator-less fields never kick | — | `validateOnMount` per field | `validateOnMount` form-level |
|
|
73
87
|
| Multiple errors per field | Native: every field holds `FieldError[]`; `getFieldErrors`/`useFieldErrors` read them; resolvers forward every schema issue | `criteriaMode: 'all'` collects all failing rules per field | Errors are arrays of messages per field | — |
|
|
74
|
-
|
|
|
75
|
-
|
|
|
76
|
-
|
|
|
88
|
+
| Non-field metadata | `setStatus` / `useStatus` — one user-owned slot for session flags, step state, non-field errors (Formik's `status` role), event-driven | — | Form/field `meta` API | `status` |
|
|
89
|
+
| SSR / hydration | `renderToString` renders initial values out of the box; server snapshot matches the client's first render (async initialValues render empty + `isLoading` on both sides) | SSR-safe | SSR-safe | SSR-safe |
|
|
90
|
+
| React 19 / Server Actions | Function `action` prop on `<Form>`: after validation passes, the validated values are converted to FormData and dispatched to it (a Server Action or a `useActionState` bridge; `onSubmit`/`onValidSubmit` also receive the values object). The `react-f0rm/server` entry's `validateValues` re-validates payloads server-side. No native no-JS submit — deliberate (see the stance below) | `<Form>` accepts a function `action` prop (native server-action-style submit, works without JS) since v7.84, and ships a `react-server` export | Documented server action integration (`createServerValidate` for server-side validation, Next.js examples) | — |
|
|
91
|
+
| Bundle size | 11.86 KB gzip core (10.81 KB brotli; emitter-external measurement) + one shared dependency (`@for-fun/event-emitter`, ~2.3 KB gzip standalone, ~+0.1 KB gzip when actually bundled, +0 when your app already depends on it) | 14.06 KB gzip (bundlephobia, v7.87.0, 2026-09) | 19.02 KB gzip (v1.33.5 measured locally: minified + gzip, `@tanstack/form-core` and `react-store` bundled, react external — the bundlephobia methodology) | ~12.8 KB gzip |
|
|
77
92
|
| Devtools | `<Devtools />` from `react-f0rm/devtools` — separate entry point, tree-shakeable, never lands in the main bundle | `@hookform/devtools` (separate package) | Built-in devtools panel | None (official) |
|
|
78
|
-
| Ecosystem maturity | New
|
|
93
|
+
| Ecosystem maturity | New — small audience, few integrations so far | Most mature: massive adoption, resolvers, UI-kit integrations, abundant examples and answers | Backed by the TanStack family, actively growing | Maintenance mode; the author recommends considering RHF or Final Form for new projects |
|
|
79
94
|
|
|
80
|
-
Bundle-size basis: every column is gzip. react-f0rm is measured on the local build —
|
|
95
|
+
Bundle-size basis: every column is gzip. react-f0rm is measured on the local build — the shipped, minified `dist/index.mjs` gzips to 11.86 KB emitter-external (10.81 KB brotli; size-limit, which minifies and tree-shakes, reports the same file with the emitter marked external — it is a runtime dependency, not bundled: ~0.1 KB gzip more when a bundler inlines it, +0 when your app already depends on it). The RHF figure is a bundlephobia API observation of v7.87.0 (2026-09); the TanStack figure is a local measurement of v1.33.5 following the bundlephobia methodology (minified + gzip, its two runtime deps bundled, react external). Formik's is the historical bundlephobia ballpark. Ours is the conservative number — measured on the built artifact, not a promise.
|
|
81
96
|
|
|
82
97
|
### Which one should you use?
|
|
83
98
|
|
|
84
|
-
**Pick react-f0rm** when you want controlled components with true per-field subscriptions (design systems, editor-like forms), one Standard Schema adapter instead of a package per validator, compile-time-checked paths, and
|
|
99
|
+
**Pick react-f0rm** when you want controlled components with true per-field subscriptions (design systems, editor-like forms), one Standard Schema adapter instead of a package per validator, compile-time-checked paths, and the smallest core of the four (11.86 KB minified gzip emitter-external / 10.81 KB brotli, one shared runtime dependency) — and you are comfortable with a young library.
|
|
85
100
|
|
|
86
|
-
**Pick React Hook Form** when
|
|
101
|
+
**Pick React Hook Form** when you want the mature ecosystem — resolvers, UI-library integrations and community answers — today. Its performance edge is gone at the rendering level: raw `register` benches at 11.7µs/change and react-f0rm's `uncontrolled: true` at 12.5µs (parity, see [Benchmarks](#benchmarks)), the controlled model is within noise of `Controller` at 100 fields and ~1.9× ahead at 1000, and TanStack's `form.Field` costs ~2.4× our per-change time. TanStack Form sits in between: choose it when the deepest possible type inference matters more to you than bundle size and per-change cost — react-f0rm's `validate` value argument is now path-inferred on `useField`/`Field` too.
|
|
87
102
|
|
|
88
|
-
**Server Actions:
|
|
103
|
+
**Server Actions: the callback `action` prop, not the native one.** `<Form>` ships a function `action` prop — after validation passes, the validated values are converted to FormData (`formDataFromValues`) and dispatched to it, e.g. a React 19 Server Action or a `useActionState` bridge. What is deliberately **not on the roadmap** is native progressive enhancement (the browser submitting without JavaScript), a `react-server` entry point, and a TanStack-style `createServerValidate` helper — a stance, not a gap. react-f0rm's source of truth is the values store, not the DOM: a no-JS submit would ship FormData keyed by JSON-stringified path keys, drop every store-only value, and skip the validation gate entirely (the [React 19 Server Actions guide](docs-site/docs/guides/react19-server-actions.md) unpacks all four failure modes). The recommended shape is the bridge — pass `action` directly, or dispatch from `onValidSubmit` via `startTransition`/`useActionState`, passing the values object rather than FormData — which keeps validation gating the action and types/nesting intact. If submitting without JavaScript loaded is a hard requirement, RHF's native `action` prop support is the better fit today.
|
|
89
104
|
|
|
90
105
|
## Usage
|
|
91
106
|
|
|
@@ -134,6 +149,17 @@ const form = useForm({initialValues: {email: ''}});
|
|
|
134
149
|
const {value, onChange} = useField({form, name: 'email'});
|
|
135
150
|
```
|
|
136
151
|
|
|
152
|
+
The result also carries `focusRef` — a stable callback ref for the input element. `setFocus` and a failed submit's first-error auto-focus ([Focusing the first error](#focusing-the-first-error)) ride the `'focusError'` event, which reaches your element through this ref; leave it off and focus requests aimed at the field are silent no-ops. It only matters for headless callers building their own input — `<Field>` wires it internally, so its users never see it:
|
|
153
|
+
|
|
154
|
+
```jsx
|
|
155
|
+
const {value, onChange, focusRef} = useField({name: 'email'});
|
|
156
|
+
<input ref={focusRef} value={value} onChange={e => onChange(e.target.value)} />
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`uncontrolled: true` pins the value at mount and skips the value subscription — typing re-renders nothing (the store still carries every write; errors/touched/disabled/validating still re-render the field), the react-hook-form `register` model at `register` parity (12.6µs vs 11.9µs bench). Bind the element with `defaultValue` instead of `value` — and attach `focusRef`, which doubles as the DOM-sync channel: bulk operations (`reset`, `setInitialValues`) write the store's value straight into the element (register-style, no render — exactly how RHF's reset clears uncontrolled inputs), while single-path writes (typing) are skipped. File inputs are exempt: their value cannot be assigned. `<Field uncontrolled />` wires all of this internally.
|
|
160
|
+
|
|
161
|
+
On unmount the field unregisters by default: its live value drops out of reads and `getValues()` (tombstone — no silent revival from `initialValues`). `shouldUnregister: false` keeps the value per field; `createForm({shouldUnregister: false})` or `<Form shouldUnregister={false}>` flips the form-wide default to react-hook-form's keep-the-value semantics, and a field-level option overrides the form-level flag in either direction.
|
|
162
|
+
|
|
137
163
|
### `subscribe`
|
|
138
164
|
|
|
139
165
|
Linked fields and other non-render side effects — province changed → clear city, autosave, analytics — should not require a mounted watching component. `subscribe` exposes the event core imperatively:
|
|
@@ -155,13 +181,13 @@ const unsubscribe = subscribe(form, {
|
|
|
155
181
|
| Option | Type | Default |
|
|
156
182
|
|---|---|---|
|
|
157
183
|
| `name` | field path, or an array of them | omitted — every emission of `event`, payload-less broadcasts (reset, …) included |
|
|
158
|
-
| `event` | `'change'` \| `'errors'` \| `'touched'` \| `'submitting'` \| `'submitCount'` | `'change'` |
|
|
184
|
+
| `event` | `'change'` \| `'errors'` \| `'touched'` \| `'validating'` \| `'submitting'` \| `'submitCount'` \| `'submitSuccessful'` \| `'disabled'` | `'change'` |
|
|
159
185
|
| `scope` | `'leaf'` \| `'branch'` | `'branch'` |
|
|
160
186
|
| `callback` | `() => void`, fired with no arguments | required |
|
|
161
187
|
|
|
162
|
-
Matching follows the event's shape. `'change'` walks the path tree: the default `'branch'` scope wakes a `'tags'` subscriber when any `tags.*` descendant is written, while `'leaf'` matches only the exact key and its ancestors. `'errors'` and `'touched'` always match the exact key — another field's error never wakes this subscriber. `'submitting'`/`'submitCount'` are payload-less, so a `name` narrows nothing. An array of names creates one subscription per path, and the returned function unsubscribes them all. A number-bearing array (`['tags', 0]`) is one segments path, not a name list — the same rule `trigger` uses.
|
|
188
|
+
Matching follows the event's shape. `'change'` walks the path tree: the default `'branch'` scope wakes a `'tags'` subscriber when any `tags.*` descendant is written, while `'leaf'` matches only the exact key and its ancestors. `'validating'` carries a path per async validator round and narrows by path exactly like `'change'` — the imperative counterpart of a per-field validating indicator. `'errors'` and `'touched'` always match the exact key — another field's error never wakes this subscriber. `'submitting'`/`'submitCount'`/`'submitSuccessful'`/`'disabled'` are payload-less, so a `name` narrows nothing. An array of names creates one subscription per path, and the returned function unsubscribes them all. A number-bearing array (`['tags', 0]`) is one segments path, not a name list — the same rule `trigger` uses.
|
|
163
189
|
|
|
164
|
-
**`subscribe` vs `useWatch`:** `useWatch` (and the `useValue`/`useError`/… readers built on it) feeds rendering — it returns a snapshot and re-renders the component when it changes. `subscribe` runs imperative code and renders nothing. Use `subscribe` for linkages and effects; reach for a hook only when the watched value itself must appear on screen.
|
|
190
|
+
**`subscribe` vs `useWatch`:** `useWatch` (and the `useValue`/`useError`/… readers built on it) feeds rendering — it returns a snapshot and re-renders the component when it changes. `subscribe` runs imperative code and renders nothing. Use `subscribe` for linkages and effects; reach for a hook only when the watched value itself must appear on screen. Its first argument is the form (`useWatch(form, 'change', getter)`), matching every other hook's context shape; the raw emitter remains accepted for back-compat. `useWatch` itself takes an optional fourth argument — `isEqual(prev, next)` — aimed at wide-scope getters that return a fresh reference per call (a whole-values selector, say): on each event the getter recomputes, and an equal verdict keeps the cached snapshot without notifying React at all — no render, not even a bailed-out one (the same contract TanStack's `useSelector` `compare` option has).
|
|
165
191
|
|
|
166
192
|
### `useFieldArray`
|
|
167
193
|
|
|
@@ -201,6 +227,21 @@ update(1, 'B'); // overwrite one value, keeping that row's id — no k
|
|
|
201
227
|
|
|
202
228
|
`replace(values)` is the refetch shape — a server response replaces the whole list — while `update(index, value)` rewrites a single row in place.
|
|
203
229
|
|
|
230
|
+
Three more options cover the react-hook-form `useFieldArray` surface:
|
|
231
|
+
|
|
232
|
+
```jsx
|
|
233
|
+
const {fields, append} = useFieldArray({
|
|
234
|
+
name: 'tags',
|
|
235
|
+
keyName: 'key', // expose the stable row id as field.key (default: 'id')
|
|
236
|
+
rules: {required: true, minLength: 1, maxLength: 5}, // validated against the whole array
|
|
237
|
+
shouldUnregister: false // keep the branch on unmount (default: form-level flag)
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
fields.map(field => <div key={field.key}>…</div>);
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`rules` check the array itself — `required` fails on an empty array, `minLength`/`maxLength` read its length — on submit and `trigger`, like every registered validator. On unmount the array branch follows the same effective `shouldUnregister` as a bound field: tombstone by default, keep the values when the option or the form-level `createForm({shouldUnregister: false})` says so.
|
|
244
|
+
|
|
204
245
|
### `useFieldArrayItem`
|
|
205
246
|
|
|
206
247
|
Per-row subscription for large arrays — the counterpart of TanStack Form's field api that `useFieldArray` alone cannot offer. `useFieldArray` subscribes to the whole branch, so any row's edit re-renders the component holding the array (and, without memoization, every row). `useFieldArrayItem` gives one row — identified by the stable `id` from `fields[i].id` — a subscription of its own:
|
|
@@ -252,6 +293,24 @@ The hook returns `{value, setValue, errors, error, name, index, form}` — the `
|
|
|
252
293
|
|
|
253
294
|
Without a paired `useFieldArray` the row is inert rather than broken: `index` is `-1`, `value` is `undefined`, and `setValue` is a no-op.
|
|
254
295
|
|
|
296
|
+
### `useTransform`
|
|
297
|
+
|
|
298
|
+
Bind a control whose display value differs from the stored value — number inputs, date pickers, selects that store objects. TanStack Form's `useTransform` counterpart, with the round trip split into two explicit directions: the store always carries the raw typed value, `toDisplay` maps it to what the control renders, `fromDisplay` maps the control's value back to the raw value on write:
|
|
299
|
+
|
|
300
|
+
```jsx
|
|
301
|
+
import {useTransform} from 'react-f0rm';
|
|
302
|
+
|
|
303
|
+
function AgeField() {
|
|
304
|
+
const age = useTransform(form, 'age', {
|
|
305
|
+
toDisplay: raw => String(raw),
|
|
306
|
+
fromDisplay: display => Number(display)
|
|
307
|
+
});
|
|
308
|
+
return <input value={age.value} onChange={e => age.onChange(e.target.value)} />;
|
|
309
|
+
}
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
`value` subscribes to 'change' at leaf scope like a controlled `useField` value — typing, programmatic `setValue` and ancestor writes re-derive it, writes elsewhere never re-render it. `onChange` writes through the user-change channel: with a field mounted at the same path, the mode/reValidateMode-gated validation fires exactly as if the user typed into a bound field (and validators receive the raw value, not the display string); with no mounted field it degrades to a plain value write. Touched marking stays a blur concern — pair with `useField` at the same path when blur semantics matter. Both directions are optional: omit `toDisplay`/`fromDisplay` for identity, and either one alone gives you a one-way transform.
|
|
313
|
+
|
|
255
314
|
### `createFormContext`
|
|
256
315
|
|
|
257
316
|
The module-level context serves one form per subtree; nesting two forms (or reusing a component under a different form) makes them fight over it. `createFormContext` builds an isolated bundle of bindings, typed against your values shape:
|
|
@@ -384,6 +443,19 @@ function Profile({onSave}) {
|
|
|
384
443
|
|
|
385
444
|
It is `false` for the whole async `onSubmit` span (not just the validation pass) and whenever any field holds an error — client validation or server backfill (`setServerErrors` lands there too). Deliberately no dirty or validating semantics: an untouched-but-clean form can submit. The snapshot recomputes on either input's event and re-renders only when the boolean itself flips. The underlying readers stay exported — `useIsSubmitting`, `useHasErrors`, `useSubmitCount` — for UIs that need the parts separately.
|
|
386
445
|
|
|
446
|
+
For the validation span itself reach for `useIsValidating(form)` — `true` while any field's async validator or pending debounce window is open and while the form-level validate round is in flight (the same marks `trigger` and submit wait out). The classic consumers are a spinner and a double-click guard on the same button:
|
|
447
|
+
|
|
448
|
+
```jsx
|
|
449
|
+
import {useIsValidating} from 'react-f0rm';
|
|
450
|
+
|
|
451
|
+
const isValidating = useIsValidating(form);
|
|
452
|
+
<button disabled={!canSubmit || isValidating} onClick={submit}>
|
|
453
|
+
{isValidating ? 'Checking…' : 'Save'}
|
|
454
|
+
</button>
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
`useCanSubmit` stays validating-free on purpose (see above), so combine the two flags when you want the stricter gate. The submission-outcome sibling `useIsSubmitSuccessful(form)` is exported alongside: `true` once `onSubmit`/`onValidSubmit` resolved without throwing, `false` when validation failed or a handler threw, `undefined` before the first submit — the usual success-banner/redirect trigger.
|
|
458
|
+
|
|
387
459
|
### Focusing the first error
|
|
388
460
|
|
|
389
461
|
After a failed submit, the offending field is focused automatically — pass `shouldFocusError: false` (on `<Form>` or `handleSubmit`) to disable; it defaults to `true`. Custom validation failures focus the first errored field through a `'focusError'` event that bound fields (like `Field`) subscribe to; native constraint failures focus the submitted form's first `:invalid` control directly.
|
|
@@ -481,11 +553,19 @@ if (await trigger(form, 'email')) {
|
|
|
481
553
|
|
|
482
554
|
Without `name` the scope is all fields plus the form-level `validate` result; with `name` only those fields' own errors count and form-level `validate` is skipped (RHF semantics). Fire-and-forget callers may ignore the promise — the validator kicks still happen synchronously.
|
|
483
555
|
|
|
556
|
+
The third argument opts into touched marking: `trigger(form, name, {shouldTouch: true})` marks every path in the triggered scope — the given names, or all registered fields when `name` is omitted — as touched once the round settles, whether validation passed or failed (react-hook-form's `trigger` semantics). Omitted, `trigger` stays validate-only:
|
|
557
|
+
|
|
558
|
+
```jsx
|
|
559
|
+
await trigger(form, 'email', {shouldTouch: true}); // 'email' is now touched, error or not
|
|
560
|
+
```
|
|
561
|
+
|
|
484
562
|
### Async validation
|
|
485
563
|
|
|
486
564
|
Async validators are first-class. Two knobs keep them cheap and race-free:
|
|
487
565
|
|
|
488
|
-
**`validateDebounce`** (on `Field`, `useField` or any bound component) delays a field's validation kicks by the given milliseconds; only the last kick inside the window runs the validator. While the timer is pending the field counts as *validating*, so `trigger` and submit wait the window out instead of racing it. The form-level `validate` gets the same contract through `validateDebounce` on `createForm`/`useForm` (see [Form-level validation](#form-level-validation)).
|
|
566
|
+
**`validateDebounce`** (on `Field`, `useField` or any bound component) delays a field's validation kicks by the given milliseconds; only the last kick inside the window runs the validator. While the timer is pending the field counts as *validating*, so `trigger` and submit wait the window out instead of racing it. The `required` rule is exempt: it runs synchronously on every kick, so a required failure shows immediately — and while it fails, the field's other validation is skipped. The form-level `validate` gets the same contract through `validateDebounce` on `createForm`/`useForm` (see [Form-level validation](#form-level-validation)).
|
|
567
|
+
|
|
568
|
+
**`asyncAlways`** (on `Field`/`useField`, with a form-level `createForm({asyncAlways})` default; TanStack Form's namesake) overrides that skip: a field whose `required` gate failed still runs its debounced validator, and the validator's result lands **alongside** the gate's errors, per-source — a passing async round clears only its own errors, the gate's verdict stays until the gate itself passes. The use case: the cheap format check fails, and the expensive backend check should still run — both verdicts belong on screen.
|
|
489
569
|
|
|
490
570
|
**`meta.signal`** — every validator's second argument carries `{form, path, signal}`. The `AbortSignal` fires as soon as the round is superseded (a newer round started, or the field unregistered), so async validators can cancel their underlying work instead of racing a stale result home:
|
|
491
571
|
|
|
@@ -519,7 +599,7 @@ setError(form, 'password', [
|
|
|
519
599
|
]);
|
|
520
600
|
```
|
|
521
601
|
|
|
522
|
-
`setError` accepts a string, a `FieldError`, an array mixing both, or `undefined` to clear. Schema resolvers pass every issue through — a value breaking several rules collects all of them (Standard Schema/zod by design, yup via `abortEarly: false`) — and `getErrors()` contributes one entry per error. For imperative clears, `clearErrors(form)` wipes every error while `clearErrors(form, name)` — one name or an array of names — clears only those fields.
|
|
602
|
+
`setError` accepts a string, a `FieldError`, an array mixing both, or `undefined` to clear. A fourth argument opts into side effects: `setError(form, 'email', 'taken', {shouldFocus: true})` focuses the field's element right after the error lands (the same `'focusError'` channel a failed submit's auto-focus uses — only mounted bound fields react). Schema resolvers pass every issue through — a value breaking several rules collects all of them (Standard Schema/zod by design, yup via `abortEarly: false`) — and `getErrors()` contributes one entry per error. For imperative clears, `clearErrors(form)` wipes every error while `clearErrors(form, name)` — one name or an array of names — clears only those fields.
|
|
523
603
|
|
|
524
604
|
### `setValue` options
|
|
525
605
|
|
|
@@ -547,11 +627,20 @@ setValue(form, 'email', 'a@b.com'); // dirty: differs from it
|
|
|
547
627
|
|
|
548
628
|
Use it whenever a programmatic write is not user input — normalized/formatted values, autofill, defaults applied after mount — and you don't want it to trip the "unsaved changes" state. `shouldDirty: true` (or omitting the flag) is the default derived behavior spelled out; unlike react-hook-form, where `setValue` skips dirty marking unless opted in, react-f0rm always derives dirty from the comparison and `false` is the opt-out.
|
|
549
629
|
|
|
630
|
+
The value argument may also be an updater function receiving the field's current value and returning the next one (TanStack Form's `setFieldValue` contract) — handy for increments and array transforms:
|
|
631
|
+
|
|
632
|
+
```jsx
|
|
633
|
+
setValue(form, 'count', c => c + 1);
|
|
634
|
+
setValue(form, 'tags', tags => [...tags, 'new']);
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
The tradeoff this implies: a function can never itself be stored as a field value through `setValue`.
|
|
638
|
+
|
|
550
639
|
Committed baselines follow the form's lifecycle: `reset`, `setInitialValues` and `resetField`/`removeField` drop them (the state they measured against is gone), and a wholesale write at an ancestor path — a `useFieldArray` rewrite, say — drops baselines beneath it, since the subtree they were committed against no longer exists.
|
|
551
640
|
|
|
552
641
|
### Writing as a user change (`changeValue`)
|
|
553
642
|
|
|
554
|
-
`setValue` is the imperative channel — `shouldValidate` kicks the field's validator unconditionally, ignoring any mode. `changeValue` is the user-change channel: the write
|
|
643
|
+
`setValue` is the imperative channel — `shouldValidate` kicks the field's validator unconditionally, ignoring any mode. `changeValue` is the user-change channel: the write rides the same core pipeline a user typing into the field would fire (`userChangeByPath` + the field-mode registry — `useField` registers its mode override on mount), so it fires exactly the validation a user typing would fire — the field's effective `mode` (per-field override included) and the form's `reValidateMode`. With no mounted field on the path it degrades to a plain `setValue`.
|
|
555
644
|
|
|
556
645
|
```jsx
|
|
557
646
|
import {changeValue} from 'react-f0rm';
|
|
@@ -561,7 +650,7 @@ import {changeValue} from 'react-f0rm';
|
|
|
561
650
|
changeValue(form, 'email', 'a@b.com');
|
|
562
651
|
```
|
|
563
652
|
|
|
564
|
-
This is the channel component libraries need when they hand a control a plain setter bound to a field (a `Control`/controlled-bridge over `useField`'s value): the mode gating — per-field override and live-error view — lives
|
|
653
|
+
This is the channel component libraries need when they hand a control a plain setter bound to a field (a `Control`/controlled-bridge over `useField`'s value): the mode gating — per-field override and live-error view — lives in the core's user-change pipeline, not in public form state, so the write must route through it rather than through a raw `setValue`.
|
|
565
654
|
|
|
566
655
|
`changeValue` takes the same options object as `setValue` (see [`setValue` options](#setvalue-options)). With a field mounted on the path, `shouldDirty: false` applies — the write lands as a commit while the field's own mode gating keeps driving validation, which is the point of this channel (`shouldValidate`/`shouldTouch` have no meaning there: forcing them would defeat the gating). With no mounted field, the options forward to the plain `setValue` fallback wholesale:
|
|
567
656
|
|
|
@@ -605,17 +694,35 @@ For declarative constraints, pass `rules` to `Field` (or any bound component —
|
|
|
605
694
|
| `minLength` | `number` | a string value is shorter — non-strings skip | `` `Must be at least ${n} characters` `` |
|
|
606
695
|
| `maxLength` | `number` | a string value is longer — non-strings skip | `` `Must be at most ${n} characters` `` |
|
|
607
696
|
| `pattern` | `{value: RegExp, message: string}` | `pattern.value.test(value)` is false | the given `message` |
|
|
697
|
+
| `validate` | `fn \| Record<string, fn>` | the callback returns an error (string or `FieldError`) | the returned message |
|
|
698
|
+
|
|
699
|
+
`validate` is react-hook-form's `register({validate})` shape: one function, or a record of named functions. Each runs after the declarative checks — and only when they passed (`required` failing short-circuits the rest). A returned error keeps its message; its `type` becomes the record key (`'validate'` for the single-function form), so consumers can switch on `error.type` like with every declarative rule:
|
|
700
|
+
|
|
701
|
+
```jsx
|
|
702
|
+
<Field
|
|
703
|
+
name="username"
|
|
704
|
+
rules={{
|
|
705
|
+
required: true,
|
|
706
|
+
validate: {
|
|
707
|
+
notReserved: v => (v === 'admin' ? 'That name is taken' : undefined),
|
|
708
|
+
noSpaces: v => (/\s/.test(v) ? 'No spaces allowed' : undefined)
|
|
709
|
+
}
|
|
710
|
+
}}
|
|
711
|
+
/>
|
|
712
|
+
```
|
|
608
713
|
|
|
609
714
|
The optional top-level `messages` record overrides messages per rule type (`min`, `max`, `minLength`, `maxLength`, `pattern`) — useful for centralizing or localizing them.
|
|
610
715
|
|
|
611
716
|
Semantics:
|
|
612
717
|
|
|
613
|
-
- A failing `required` short-circuits the rest — an empty value reports only its `required` error, not a full panel.
|
|
718
|
+
- A failing `required` short-circuits the rest — an empty value reports only its `required` error, not a full panel — and skips `validate` entirely for that kick: the async check never sees an empty value (`asyncAlways` overrides that skip — see [Async validation](#async-validation)).
|
|
719
|
+
- `required` runs synchronously on every kick, even under a positive `validateDebounce`: its error shows on the keystroke and clears as soon as the value is filled.
|
|
614
720
|
- Every other failing rule collects into one ordered `FieldError[]` (see [Multiple errors per field](#multiple-errors-per-field)).
|
|
615
|
-
-
|
|
616
|
-
|
|
721
|
+
- The other rules compose with `validate`: they run first, then `validate` (awaited when async), merging both sources' errors with rules ahead. They ride the same pipeline as `validate` — `mode`, `reValidateMode`, `validateDebounce` and `meta.signal` all apply unchanged.
|
|
722
|
+
|
|
723
|
+
Rules render as **native constraint attributes** too: the declarative subset (`required`, `min`, `max`, `minLength`, `maxLength`, `pattern`) lands on the element for browser and assistive-tech hints — `:invalid`/`:user-invalid` styling, screen-reader announcements, mobile input modes. The store pipeline stays the source of truth for messages: rule failures still land in the form's error state and render through `renderError`/`aria-invalid`, never through a browser bubble you don't control. A user-passed `required`/`pattern`/… prop always wins over the derived attribute; `validate` callbacks have no native counterpart and are skipped.
|
|
617
724
|
|
|
618
|
-
|
|
725
|
+
Native constraints vs `rules`: HTML attributes (`required`, `type="email"`, `min`, …) keep running through the browser's `checkValidity`, whose bubble remains the pre-submit fallback. `rules` is the state-side alternative — failures are queryable (`getErrors`, `error`, `errors`), renderable by any UI, and carry your own messages — with the native attributes layered on top for a11y and styling. Prefer `rules` whenever the error text must be controlled.
|
|
619
726
|
|
|
620
727
|
### Form-level validation
|
|
621
728
|
|
|
@@ -653,6 +760,21 @@ const form = useForm({
|
|
|
653
760
|
|
|
654
761
|
The `AbortSignal` fires as soon as the round is superseded — a newer round started, which under a positive `validateDebounce` means a kick landed during the in-flight round's window — so async validators can cancel their underlying work instead of racing a stale result home. Stale results are dropped independently by the round gate, so validators that ignore the signal stay correct too. Without `validateDebounce` (`0`/omitted) the validate runs once per `trigger`/submit exactly as before; it still receives the meta argument, but nothing supersedes an immediate round, so its signal never fires.
|
|
655
762
|
|
|
763
|
+
#### Reading form-level errors
|
|
764
|
+
|
|
765
|
+
Errors that belong to no single field need a slot to land in: a form-level `validate` record may return a `_form` entry, and the Standard Schema adapter drops every path-less issue there (see [Schema validation](#schema-validation)). That reserved key is exported as `FORM_ERROR`, so the magic string never has to be hand-written:
|
|
766
|
+
|
|
767
|
+
```jsx
|
|
768
|
+
import {FORM_ERROR, useFormError, useFormErrors} from 'react-f0rm';
|
|
769
|
+
|
|
770
|
+
function FormErrorBanner({form}) {
|
|
771
|
+
const error = useFormError(form); // first form-level error's message
|
|
772
|
+
return error ? <p role="alert">{error}</p> : null;
|
|
773
|
+
}
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
`useFormError(form)` reads the slot's first message (`undefined` while clean) — the classic consumer is one banner above the submit button. `useFormErrors(form)` reads every error stored under the key (`FieldError[]`, stable reference between unrelated events). The imperative twins are `getError(form, FORM_ERROR)` and `getFieldErrors(form, FORM_ERROR)`, and writes go through the same `setError(form, FORM_ERROR, …)` every field uses.
|
|
777
|
+
|
|
656
778
|
#### Re-running on dependent field changes (`validateDeps`)
|
|
657
779
|
|
|
658
780
|
By default the form-level `validate` runs on `trigger` and submit only — a cross-field error stays on screen even after the user edits the field that would fix it. `validateDeps` declares the fields whose **user changes re-run the form-level `validate`**:
|
|
@@ -806,6 +928,8 @@ function FormStatus({form}) {
|
|
|
806
928
|
|
|
807
929
|
Both hooks expose user-facing dotted paths (`'a.b'`, `'a.0.c'`). The imperative counterparts `getDirtyFields(form)` and `getTouchedFields(form)` return the same shapes without subscribing.
|
|
808
930
|
|
|
931
|
+
For one field, `useIsFieldDirty(form, name)` subscribes at leaf scope — the per-field twin of `useIsDirty(form)`, applying the same rule `getFieldState(form, name).isDirty` does (committed `shouldDirty: false` baselines included; a leaf under a wholesale ancestor write reports clean, since dirtiness belongs to the branch that diverged). `useField` carries the same flag as `field.isDirty`, live in controlled mode; in `uncontrolled: true` mode it is pinned at mount like `value` (typing never re-renders the field), so `useIsFieldDirty` is the live channel there.
|
|
932
|
+
|
|
809
933
|
### Seeding new initial values
|
|
810
934
|
|
|
811
935
|
`setInitialValues(form, values)` swaps the baseline by **content**, not reference: passing a fresh object with equal content (the inline literal a re-render recreates) is a no-op — committed edits survive — while genuinely changed content re-seeds: live values and tombstones are cleared, touched flags and errors survive. Same value semantics `useForm({initialValues})`/`<Form initialValues>` sync with, so the editor-page shape works without memoizing the literal or double-passing it:
|
|
@@ -817,15 +941,37 @@ const article = useData<Article>() ?? undefined;
|
|
|
817
941
|
const form = useForm({initialValues: articleToValues(article)});
|
|
818
942
|
```
|
|
819
943
|
|
|
944
|
+
### Async initial values
|
|
945
|
+
|
|
946
|
+
`initialValues` accepts a Promise, or a thunk returning a value or Promise — react-hook-form's async `defaultValues` shape. The form starts empty with `isLoading: true`, and when the source resolves, its values become the baseline (setInitialValues semantics: value subscribers re-sync, dirty/touched start clean, `reset()` returns to the resolved values):
|
|
947
|
+
|
|
948
|
+
```jsx
|
|
949
|
+
const form = useForm({
|
|
950
|
+
initialValues: () => fetchUser(id).then(u => ({name: u.name, email: u.email}))
|
|
951
|
+
});
|
|
952
|
+
const isLoading = useIsLoading(form); // also on useFormState(form).isLoading
|
|
953
|
+
|
|
954
|
+
if (isLoading) return <Spinner />;
|
|
955
|
+
return <Form form={form}>…</Form>;
|
|
956
|
+
```
|
|
957
|
+
|
|
958
|
+
Notes:
|
|
959
|
+
|
|
960
|
+
- The thunk runs at create time — keep its identity stable (`useMemo`, module scope) when passing it inline; StrictMode double-invokes it in development, like every render-phase call.
|
|
961
|
+
- A rejected source keeps the form empty, flips `isLoading` off and logs the error in DEV — attach a `.catch` on the source to handle it.
|
|
962
|
+
- SSR renders the form empty with `isLoading: true` on both sides, so hydration matches; the values land client-side after the fetch (pass the server-resolved record to hydrate eagerly instead).
|
|
963
|
+
|
|
820
964
|
### Resetting
|
|
821
965
|
|
|
822
|
-
`reset(form, initialValues?)` wipes values, errors, touched, tombstones and the submission flags (`isSubmitting`, `submitCount`, `isSubmitSuccessful`). The second argument installs a fresh baseline. The third opts into keeping slices of state through the reset:
|
|
966
|
+
`reset(form, initialValues?)` wipes values, errors, touched, tombstones and the submission flags (`isSubmitting`, `submitCount`, `isSubmitSuccessful`). The second argument installs a fresh baseline; omitted (or `undefined`), the form keeps its current `initialValues` and every field simply returns to its initial value — the plain `reset(form)` "undo everything" shape. The third opts into keeping slices of state through the reset:
|
|
823
967
|
|
|
824
968
|
```jsx
|
|
825
969
|
import {reset} from 'react-f0rm';
|
|
826
970
|
|
|
971
|
+
reset(form); // back to the current initialValues
|
|
827
972
|
reset(form, freshRecord); // full reset to the new baseline
|
|
828
973
|
reset(form, freshRecord, {keepDirtyValues: true}); // dirty drafts survive
|
|
974
|
+
reset(form, undefined, {keepTouched: true}); // reset, keep touched flags
|
|
829
975
|
```
|
|
830
976
|
|
|
831
977
|
`keepDirtyValues` is the refetch shape: reload the record from the server, but fields the user already edited keep their live values (dirtiness is measured against the pre-reset initialValues; clean fields fall back to the new baseline):
|
|
@@ -918,6 +1064,38 @@ async function onSubmit(values) {
|
|
|
918
1064
|
|
|
919
1065
|
The message then renders under the field through the same error machinery (`renderError`, `useError` — see [Accessibility](#accessibility)), and the field's `aria-invalid`/`aria-describedby` wiring kicks in automatically. Existing errors are cleared first — a fresh response describes the current state; pass `{keepExisting: true}` to layer instead. String values land as one error, string arrays as several; an empty array clears that field.
|
|
920
1066
|
|
|
1067
|
+
## Server-side validation
|
|
1068
|
+
|
|
1069
|
+
The client-side gate is UX, not security — payloads must be re-validated where they arrive. `react-f0rm/server` is the entry for that: a separate module graph with zero React, safe to import from Server Actions, RSC and plain Node, and — like the resolvers and devtools — never re-exported from the main entry, so client builds that never validate server-side stay at baseline size. Its export is one function:
|
|
1070
|
+
|
|
1071
|
+
```jsx
|
|
1072
|
+
import {validateValues} from 'react-f0rm/server';
|
|
1073
|
+
|
|
1074
|
+
// A Server Action — or any handler that receives a payload
|
|
1075
|
+
export async function saveProfile(values) {
|
|
1076
|
+
const {valid, values: parsed, errors} = await validateValues(values, {
|
|
1077
|
+
validate: values =>
|
|
1078
|
+
values.email.includes('@') ? undefined : {email: 'Invalid email'}
|
|
1079
|
+
});
|
|
1080
|
+
if (!valid) return {errors};
|
|
1081
|
+
return save(parsed);
|
|
1082
|
+
}
|
|
1083
|
+
```
|
|
1084
|
+
|
|
1085
|
+
`validateValues(values, options?)` spins up one throwaway form from `options` (its `initialValues` forced to `values`), runs a whole-form `trigger`, and reads the outcome back — async validators and `validateDebounce` windows are awaited, so the result is settled, never a mid-flight snapshot. The rules come from `options.validate`, the form-level validator: field validators register through mounted fields and nothing is mounted on the server, so pass `standardSchemaFormValidator(schema)` (from `react-f0rm/resolvers/standard-schema`) or a hand-written `validate`. The result carries:
|
|
1086
|
+
|
|
1087
|
+
- `valid` — `trigger`'s boolean. An invalid payload is a normal outcome, never a rejection: both branches are interesting on the server (persist vs. bounce back).
|
|
1088
|
+
- `values` — the tree after the round. A schema validator's parsed output (coerce/transform included) becomes the baseline, so this is the tree to persist, not necessarily the object passed in.
|
|
1089
|
+
- `errors` — the flat `{path, type, message}` entries, the same list `getErrors` hands out on the client. A one-liner lands a failed round back on the client form through the [Server-side errors](#server-side-errors) channel:
|
|
1090
|
+
|
|
1091
|
+
```jsx
|
|
1092
|
+
setServerErrors(form, Object.fromEntries(errors.map(e => [e.path, e.message])));
|
|
1093
|
+
```
|
|
1094
|
+
|
|
1095
|
+
The entry also re-exports `VALIDATION_OUTCOME`/`ValidationOutcome` for building branded validator results server-side without importing the package root (which would drag the React graph back in).
|
|
1096
|
+
|
|
1097
|
+
TanStack Form's counterpart is `createServerValidate`; theirs wraps the round inside a generated server action, while `validateValues` stays a plain function over values. That is the same stance as the client bridge — no `action` prop, no generated handler ("Server Actions: bridge, not first-class" in [Which one should you use?](#which-one-should-you-use), and the [React 19 Server Actions guide](docs-site/docs/guides/react19-server-actions.md) for the why): react-f0rm composes into your framework's handler instead of owning it.
|
|
1098
|
+
|
|
921
1099
|
## TypeScript
|
|
922
1100
|
|
|
923
1101
|
`FieldPath<T>` and `PathValue<T, P>` make field names and value types compile-time checked:
|
|
@@ -937,8 +1115,10 @@ type ValuesPath = FieldPath<Values>;
|
|
|
937
1115
|
type UserName = PathValue<Values, 'user.name'>;
|
|
938
1116
|
|
|
939
1117
|
function UserNameField() {
|
|
940
|
-
// value is inferred as string;
|
|
941
|
-
//
|
|
1118
|
+
// value is inferred as string; a path outside FieldPath<Values> — a
|
|
1119
|
+
// typo or an untyped string variable — is a compile error on these
|
|
1120
|
+
// generic APIs (react-hook-form parity). Segment arrays
|
|
1121
|
+
// (['user', 'name']) stay accepted and read as `any`.
|
|
942
1122
|
const {value, onChange} = useField<Values, 'user.name'>({name: 'user.name'});
|
|
943
1123
|
return <input value={value} onChange={e => onChange(e.target.value)} />;
|
|
944
1124
|
}
|
|
@@ -946,6 +1126,11 @@ function UserNameField() {
|
|
|
946
1126
|
|
|
947
1127
|
The same generics work on `getValue`/`setValue`/`getError` and the other path-taking helpers.
|
|
948
1128
|
|
|
1129
|
+
The strictness is on the generic path APIs (`useField`, `setValue`, `getValue`, `useValue`, …): an unknown path fails there. Two escape hatches stay deliberately wide, because their names are runtime-computed by nature:
|
|
1130
|
+
|
|
1131
|
+
- **Segment arrays** (`['items', 0]`): accepted everywhere, value reads as `any` — the dynamic-path escape hatch.
|
|
1132
|
+
- **Runtime-dynamic entry points**: `useFieldArray`, `useFieldArrayItem`, `removeField`, `setTouched`, `setFocus`, `trigger` and `clearErrors` take the wide `Name` type, so `name={dynamicString}` keeps compiling without casts.
|
|
1133
|
+
|
|
949
1134
|
The default context is typed too — `useFormContext<Values>()` returns a `Form<Values>`, so downstream components drop the `any` dances (`eslint-disable no-unsafe-*`, value casts) without buying into `createFormContext`:
|
|
950
1135
|
|
|
951
1136
|
```tsx
|
|
@@ -1006,6 +1191,17 @@ import {Select} from 'react-f0rm';
|
|
|
1006
1191
|
</Select>
|
|
1007
1192
|
```
|
|
1008
1193
|
|
|
1194
|
+
**File inputs.** The DOM keeps `<input type="file">`'s `value` read-only — it holds a fake file path string and throws if you assign to it, so the control cannot be driven like other inputs. The controlled model adapts by storing the selection itself: leave the input uncontrolled and commit the chosen `File` object on change:
|
|
1195
|
+
|
|
1196
|
+
```jsx
|
|
1197
|
+
function AvatarPicker() {
|
|
1198
|
+
const {onChange} = useField({name: 'avatar'});
|
|
1199
|
+
return <input type="file" accept="image/*" onChange={e => onChange(e.target.files?.[0])} />;
|
|
1200
|
+
}
|
|
1201
|
+
// getValues(form).avatar is now the File itself — on submit it is
|
|
1202
|
+
// ready for the request body (FormData/multipart), no DOM read needed.
|
|
1203
|
+
```
|
|
1204
|
+
|
|
1009
1205
|
## Server-side Rendering
|
|
1010
1206
|
|
|
1011
1207
|
Form state lives in synchronously readable structures seeded from `initialValues`, and every subscription goes through `useSyncExternalStore` with a `getServerSnapshot` that computes the same snapshot as the client's first render. `renderToString` therefore renders form-driven components with their initial values out of the box, and `hydrateRoot` matches the server markup — no provider shims, no `typeof window` guards:
|
|
@@ -1025,6 +1221,13 @@ Coming from another library? [Migrating from TanStack Form](./docs/from-tanstack
|
|
|
1025
1221
|
- [Migrating from React Hook Form](docs-site/docs/migration/from-react-hook-form.md)
|
|
1026
1222
|
- [Migrating from TanStack Form](docs-site/docs/migration/from-tanstack-form.md)
|
|
1027
1223
|
|
|
1224
|
+
## Breaking changes in 1.0
|
|
1225
|
+
|
|
1226
|
+
- **`react >=18` peer.** The `use-sync-external-store` shim is gone — subscriptions use React's native `useSyncExternalStore`. The event emitter stopped being vendored: `src/emitter.ts` is now a facade over the `@for-fun/event-emitter` runtime dependency (external in ESM/CJS builds, so apps already depending on it dedupe the copy; the UMD bundle stays self-contained).
|
|
1227
|
+
- **`reset` keep-flag split.** `keepIsSubmitted` now keeps the new `isSubmitted` flag (set on every submit attempt, cleared by reset — RHF's `formState.isSubmitted` semantics). Keeping the last submit's success flag is the new `keepIsSubmitSuccessful`. Previously `keepIsSubmitted` controlled `isSubmitSuccessful`; migration is a one-word rename for that use case.
|
|
1228
|
+
- **`useFieldArray` unmount.** Unmounting the array now removes its branch by default (tombstone), exactly like a bound field — previously the values silently stayed. Keep them with `shouldUnregister: false` per array, or `createForm({shouldUnregister: false})` form-wide.
|
|
1229
|
+
- **`setValue` functions are updaters.** `setValue(form, 'count', c => c + 1)` updates from the current value (TanStack's `setFieldValue` contract); a function can no longer itself be stored as a field value through `setValue`.
|
|
1230
|
+
|
|
1028
1231
|
## Breaking changes in 0.2
|
|
1029
1232
|
|
|
1030
1233
|
v0.2 structures the error model (`FieldError`), changes unregister/reset/native-validation semantics, and more — see the [v0.1 → v0.2 migration guide](docs-site/docs/migration/v0.1-to-v0.2.md).
|