react-f0rm 1.3.0 → 1.4.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 +88 -1143
- package/devtools.d.ts +1 -0
- package/devtools.js +1 -0
- package/dist/array-3hAjl6Bz.d.ts +160 -0
- package/dist/devtools/index.cjs.js +1 -1
- package/dist/devtools/index.cjs.js.map +1 -1
- package/dist/devtools/index.d.cts +34 -0
- package/dist/devtools/index.d.mts +34 -0
- package/dist/devtools/index.d.ts +3 -2
- package/dist/devtools/index.mjs +1 -1
- package/dist/devtools/index.mjs.map +1 -1
- package/dist/errors-8oPux7GR.cjs.js +2 -0
- package/dist/errors-8oPux7GR.cjs.js.map +1 -0
- package/dist/errors-ClH3eV1R.mjs +2 -0
- package/dist/errors-ClH3eV1R.mjs.map +1 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.cts +1833 -0
- package/dist/index.d.mts +1833 -0
- package/dist/index.d.ts +372 -117
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +859 -225
- 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 +1 -1
- package/dist/persist.cjs.js.map +1 -1
- package/dist/persist.d.cts +49 -0
- package/dist/persist.d.mts +49 -0
- package/dist/persist.mjs +1 -1
- package/dist/persist.mjs.map +1 -1
- 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.cts +2 -0
- package/dist/resolvers/standard-schema.d.mts +2 -0
- package/dist/resolvers/standard-schema.d.ts +1 -67
- 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.cts +6 -0
- package/dist/resolvers/yup.d.mts +6 -0
- package/dist/resolvers/yup.d.ts +0 -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.cts +6 -0
- package/dist/resolvers/zod.d.mts +6 -0
- package/dist/resolvers/zod.d.ts +0 -1
- package/dist/resolvers/zod.mjs +1 -1
- package/dist/resolvers/zod.mjs.map +1 -1
- package/dist/server/index.cjs.js +1 -1
- package/dist/server/index.cjs.js.map +1 -1
- package/dist/server/index.d.cts +106 -0
- package/dist/server/index.d.mts +106 -0
- package/dist/server/index.d.ts +31 -2
- package/dist/server/index.mjs +1 -1
- package/dist/server/index.mjs.map +1 -1
- package/dist/standard-schema-CYbnugL7.d.ts +1184 -0
- package/dist/standardSchema-BpZvg0tZ.mjs +2 -0
- package/dist/standardSchema-BpZvg0tZ.mjs.map +1 -0
- package/dist/standardSchema-CxV_DhBO.cjs.js +2 -0
- package/dist/standardSchema-CxV_DhBO.cjs.js.map +1 -0
- package/dist/validate-BEjNsNvd.mjs +2 -0
- package/dist/validate-BEjNsNvd.mjs.map +1 -0
- package/dist/validate-BvN6hiEG.cjs.js +2 -0
- package/dist/validate-BvN6hiEG.cjs.js.map +1 -0
- package/dist/values-Bod74Kzu.mjs +2 -0
- package/dist/values-Bod74Kzu.mjs.map +1 -0
- package/dist/values-DKpOCD5J.cjs.js +2 -0
- package/dist/values-DKpOCD5J.cjs.js.map +1 -0
- package/package.json +72 -27
- package/persist.d.ts +1 -0
- package/persist.js +1 -0
- package/resolvers/standard-schema.d.ts +1 -0
- package/resolvers/standard-schema.js +1 -0
- package/resolvers/yup.d.ts +1 -0
- package/resolvers/yup.js +1 -0
- package/resolvers/zod.d.ts +1 -0
- package/resolvers/zod.js +1 -0
- package/server.d.ts +1 -0
- package/server.js +1 -0
- package/dist/errors-BKrUdpfI.cjs.js +0 -2
- package/dist/errors-BKrUdpfI.cjs.js.map +0 -1
- package/dist/errors-CrQBddrJ.mjs +0 -2
- package/dist/errors-CrQBddrJ.mjs.map +0 -1
- package/dist/form-CeKSBs31.d.ts +0 -486
- package/dist/validate-CNtuUhmk.mjs +0 -2
- package/dist/validate-CNtuUhmk.mjs.map +0 -1
- package/dist/validate-Cl4ksNFu.cjs.js +0 -2
- package/dist/validate-Cl4ksNFu.cjs.js.map +0 -1
- package/dist/validate-nksgv1pR.d.ts +0 -272
- package/dist/values-Cu6awQOJ.cjs.js +0 -2
- package/dist/values-Cu6awQOJ.cjs.js.map +0 -1
- package/dist/values-DRY-a32G.mjs +0 -2
- package/dist/values-DRY-a32G.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -2,32 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/wmzy/react-f0rm/actions/workflows/ci.yml)
|
|
4
4
|
[](https://www.npmjs.com/package/react-f0rm)
|
|
5
|
-
[](https://bundlephobia.com/package/react-f0rm)
|
|
5
|
+
[](https://bundlephobia.com/package/react-f0rm)
|
|
6
6
|
[](https://opensource.org/licenses/ISC)
|
|
7
7
|
|
|
8
8
|
A headless, event-driven React form library with field-level subscriptions.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
**The pitch in one sentence:** a lighter, faster TanStack Form — same field-level-subscription model and headless API, ~25% smaller core, 2.4× faster controlled-field changes — plus react-hook-form's escape hatches (`register` at `{...register('x')}` parity, `uncontrolled` mode, declarative `rules`, nested `formState.errors`-style error reads) and one Standard Schema adapter for every validation library.
|
|
11
|
+
|
|
12
|
+
- [Docs site](https://wmzy.github.io/react-f0rm/) — guides, API reference, migration
|
|
13
|
+
- [Benchmarks](https://wmzy.github.io/react-f0rm/benchmarks) · [Comparison](https://wmzy.github.io/react-f0rm/comparison) · [Storybook gallery](https://wmzy.github.io/react-f0rm/storybook)
|
|
14
|
+
- Coming from TanStack Form? [Migrating from TanStack Form](./docs/from-tanstack-form.md) is the one-page concept map.
|
|
11
15
|
|
|
12
16
|
## Features
|
|
13
17
|
|
|
14
|
-
- **Field-level subscriptions.** Editing one field re-renders exactly that field's component
|
|
15
|
-
- **One shared runtime dependency.** The event core is `@for-fun/event-emitter` (
|
|
16
|
-
- **
|
|
17
|
-
- **One schema adapter for every library.**
|
|
18
|
-
- **
|
|
19
|
-
- **
|
|
20
|
-
- **
|
|
21
|
-
- **
|
|
22
|
-
- **
|
|
23
|
-
- **
|
|
24
|
-
-
|
|
25
|
-
- **
|
|
26
|
-
- **
|
|
27
|
-
- **
|
|
28
|
-
- **
|
|
29
|
-
- **
|
|
30
|
-
-
|
|
18
|
+
- **Field-level subscriptions.** Editing one field re-renders exactly that field's component. State is read through React's native `useSyncExternalStore` — tearing-safe under concurrent rendering. `uncontrolled: true` drops the value subscription entirely (react-hook-form `register` model: typing re-renders nothing, bench parity at ~12µs/change).
|
|
19
|
+
- **One shared runtime dependency.** The event core is a facade over `@for-fun/event-emitter` (external in ESM/CJS, so apps sharing it dedupe the copy; inlined only in the UMD bundle). The tradeoff is recorded in [ADR-0001](./docs/decisions/0001-event-emitter-facade.md).
|
|
20
|
+
- **Compile-time-checked paths.** `FieldPath<T>` / `PathValue<T, P>`: typo'd field names fail at compile time on the generic APIs; `FieldErrors<T>` types the error record; an `OpaqueTypes` registry stops recursion into Date/Dayjs-style leaves. See the [TypeScript guide](https://wmzy.github.io/react-f0rm/guides/typescript).
|
|
21
|
+
- **One schema adapter for every library.** Standard Schema v1 covers zod v3.24+/v4, valibot v1, arktype and more — plus `createForm({validate: schema})` accepts a schema directly and infers `TValues` from its output. See [Validation](https://wmzy.github.io/react-f0rm/guides/validation).
|
|
22
|
+
- **Async validation with cancellation.** `validateDebounce` per field + an `AbortSignal` in every validator's meta — superseded rounds cancel their in-flight work; pending debounce counts as validating so submit waits; `asyncAlways` lands a gate's verdict and the validator's result per-source.
|
|
23
|
+
- **Multiple errors per field.** Every field holds an ordered `FieldError[]`; resolvers forward every schema issue.
|
|
24
|
+
- **Headless everywhere.** You own the markup — `useField`/`handleSubmit`/`subscribe`/`watch` work without the DOM (React Native included); `Field`/`Checkbox`/`Select`/`Form` are thin DOM adapters over the same hooks. See [Headless & React Native](https://wmzy.github.io/react-f0rm/guides/headless-react-native).
|
|
25
|
+
- **Selector primitive.** `useStore(form, selector, isEqual?)` is the TanStack `useStore` counterpart; `useValues(form)` watches the whole tree (RHF `watch()` with no arguments); `useWatch` with the `isEqual` bailout covers single events; `useFormState` is the built-in aggregate. See [Hooks Reference](https://wmzy.github.io/react-f0rm/guides/hooks-reference).
|
|
26
|
+
- **React 19 / Server Actions.** `<Form action>` dispatches validated, schema-coerced values as `FormData`; an action returning `{errors: {field: msg}}` hydrates the fields as server errors; `react-f0rm/server` re-validates payloads without React and parses incoming FormData back with `valuesFromFormData`. See the [Server Actions guide](https://wmzy.github.io/react-f0rm/guides/react19-server-actions).
|
|
27
|
+
- **Accessibility wired in.** `aria-invalid` + `aria-describedby` → `fieldErrorId(name)` on every bound field; `renderError` completes the `role="alert"` chain.
|
|
28
|
+
- **`form.register(name)`** — react-hook-form's `register` contract, no hook required: spread the returned props onto an uncontrolled element (`<input {...form.register('email')} />`), the element never re-renders, and the store still carries every write (`getValues`/submit/validation read it). Works in dynamic lists, conditional fields and non-React adapters; `rules`/`mode`/`valueAsNumber` ride the same pipeline `useField` uses. `useField({uncontrolled: true})` stays the hook-side counterpart.
|
|
29
|
+
- **Spreadable `inputProps`.** `<input {...field.inputProps} />` binds value, event extraction (`eventToValue`/`valueAsNumber`/checkbox/file auto-detection), blur, the focus channel, `disabled` and the `aria-invalid`/`aria-describedby` chain in one spread — while the headless `onChange(value)` keeps serving design-system controls that hand raw values.
|
|
30
|
+
- **Nested error tree.** `useErrorsTree(form)` / `getErrorsTree(form)` read errors as `errors.items?.[0]?.name` — the typed optional-chain shape RHF's `formState.errors` uses — alongside the flat dotted record (`useErrors`). One cache, both views, stable references.
|
|
31
|
+
- **Form-level validation cadence.** `createForm({validateMode: 'onChange' | 'onBlur'})` re-runs the form-level `validate` on every user change/blur — TanStack `validators.onChange/onBlur` parity without enumerating `validateDeps`; rounds own their errors, so a passing re-run clears what the last round wrote.
|
|
32
|
+
- **Disabled subtrees.** A field declared `disabled: true` disables its descendants (RHF subtree semantics); a descendant opts back out with `disabled: false`. The form-level flag still disables everything.
|
|
33
|
+
- **Tombstone unregister, async initial values, declarative `rules`** (store-side errors + native constraint attributes), `validateOnMount`, `validateDeps` cross-field re-runs, `useTransform` async transforms, `createFormContext` typed isolated contexts, `reset`/`resetField` with RHF-parity keep-flags, `<Devtools />` from `react-f0rm/devtools`, `react-f0rm/persist` — see the [docs site](https://wmzy.github.io/react-f0rm/) for the full surface.
|
|
34
|
+
- **14.33 KB gzip core** (13.0 KB brotli, emitter-external measurement); devtools/server/persist/resolvers ship as separate tree-shakeable entries.
|
|
31
35
|
|
|
32
36
|
## Install
|
|
33
37
|
|
|
@@ -36,73 +40,8 @@ Requires React 18 or newer (native `useSyncExternalStore`, no shim).
|
|
|
36
40
|
```sh
|
|
37
41
|
npm i react-f0rm
|
|
38
42
|
```
|
|
39
|
-
or
|
|
40
|
-
```
|
|
41
|
-
yarn add react-f0rm
|
|
42
|
-
```
|
|
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
|
-
|
|
46
|
-
## Benchmarks
|
|
47
|
-
|
|
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).
|
|
49
|
-
|
|
50
|
-
| Scenario | react-f0rm | Baseline | Speedup |
|
|
51
|
-
|---|---|---|---|
|
|
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× |
|
|
54
|
-
| Components re-rendered per change | 1 of 100 `Field`s | — | — |
|
|
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) | — | — |
|
|
60
|
-
|
|
61
|
-
Notes:
|
|
62
|
-
|
|
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.
|
|
66
|
-
|
|
67
|
-
Reproduce with:
|
|
68
|
-
|
|
69
|
-
```sh
|
|
70
|
-
npx vitest bench --run test/bench/render.bench.ts test/bench/getValues.bench.ts
|
|
71
|
-
npx vitest bench --run test/bench/scale.bench.ts # the three scale scenarios above
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
## Comparison
|
|
75
|
-
|
|
76
|
-
react-f0rm vs the established options. react-f0rm figures come from this repo (size-limit, tinybench — see [Benchmarks](#benchmarks)); competitor sizes are Bundlephobia gzip observations and drift between versions, so treat them as ballpark rather than gospel.
|
|
77
|
-
|
|
78
|
-
| | react-f0rm | React Hook Form | TanStack Form | Formik |
|
|
79
|
-
|---|---|---|---|---|
|
|
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` |
|
|
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` |
|
|
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 |
|
|
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 | — |
|
|
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 |
|
|
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) |
|
|
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 |
|
|
94
|
-
|
|
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.
|
|
96
|
-
|
|
97
|
-
### Which one should you use?
|
|
98
|
-
|
|
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.
|
|
100
|
-
|
|
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.
|
|
102
|
-
|
|
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.
|
|
104
43
|
|
|
105
|
-
##
|
|
44
|
+
## Quick Start
|
|
106
45
|
|
|
107
46
|
```jsx
|
|
108
47
|
import React from 'react';
|
|
@@ -111,1123 +50,129 @@ import {Form, Field} from 'react-f0rm';
|
|
|
111
50
|
export default function Register() {
|
|
112
51
|
return (
|
|
113
52
|
<Form
|
|
114
|
-
initialValues={{name: '
|
|
53
|
+
initialValues={{name: '', email: ''}}
|
|
115
54
|
onValidSubmit={values => console.log(values)}
|
|
116
55
|
>
|
|
117
|
-
<Field name="name" />
|
|
118
|
-
<Field name="email" />
|
|
56
|
+
<Field name="name" rules={{required: true}} renderError={e => <em>{e}</em>} />
|
|
57
|
+
<Field name="email" type="email" />
|
|
119
58
|
<button>SUBMIT</button>
|
|
120
59
|
</Form>
|
|
121
60
|
);
|
|
122
61
|
}
|
|
123
62
|
```
|
|
124
63
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
### `useField`
|
|
128
|
-
|
|
129
|
-
For full control over field rendering:
|
|
64
|
+
Headless — the same form without `<Field>`'s DOM:
|
|
130
65
|
|
|
131
66
|
```jsx
|
|
132
67
|
import {useField} from 'react-f0rm';
|
|
133
68
|
|
|
134
69
|
function CustomField({name}) {
|
|
135
|
-
const {value, onChange, onBlur, error,
|
|
70
|
+
const {value, onChange, onBlur, error, focusRef} = useField({name});
|
|
136
71
|
return (
|
|
137
72
|
<div>
|
|
138
|
-
<input value={value} onChange={e => onChange(e.target.value)} onBlur={onBlur} />
|
|
73
|
+
<input ref={focusRef} value={value ?? ''} onChange={e => onChange(e.target.value)} onBlur={onBlur} />
|
|
139
74
|
{error && <span role="alert">{error}</span>}
|
|
140
75
|
</div>
|
|
141
76
|
);
|
|
142
77
|
}
|
|
143
78
|
```
|
|
144
79
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
```jsx
|
|
148
|
-
const form = useForm({initialValues: {email: ''}});
|
|
149
|
-
const {value, onChange} = useField({form, name: 'email'});
|
|
150
|
-
```
|
|
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:
|
|
80
|
+
Or one spread — `inputProps` is the DOM-boundary adapter over the same handlers (event extraction, focus channel, a11y chain included):
|
|
153
81
|
|
|
154
82
|
```jsx
|
|
155
|
-
|
|
156
|
-
|
|
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
|
-
|
|
163
|
-
### `subscribe`
|
|
164
|
-
|
|
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:
|
|
166
|
-
|
|
167
|
-
```jsx
|
|
168
|
-
import {createForm, subscribe, getValue, setValue} from 'react-f0rm';
|
|
169
|
-
|
|
170
|
-
const form = createForm({initialValues: {province: '', city: ''}});
|
|
171
|
-
|
|
172
|
-
const unsubscribe = subscribe(form, {
|
|
173
|
-
name: 'province',
|
|
174
|
-
callback: () => {
|
|
175
|
-
// Read fresh state through the getters inside the callback.
|
|
176
|
-
if (getValue(form, 'city')) setValue(form, 'city', '');
|
|
177
|
-
}
|
|
178
|
-
});
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
| Option | Type | Default |
|
|
182
|
-
|---|---|---|
|
|
183
|
-
| `name` | field path, or an array of them | omitted — every emission of `event`, payload-less broadcasts (reset, …) included |
|
|
184
|
-
| `event` | `'change'` \| `'errors'` \| `'touched'` \| `'validating'` \| `'submitting'` \| `'submitCount'` \| `'submitSuccessful'` \| `'disabled'` | `'change'` |
|
|
185
|
-
| `scope` | `'leaf'` \| `'branch'` | `'branch'` |
|
|
186
|
-
| `callback` | `() => void`, fired with no arguments | required |
|
|
187
|
-
|
|
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.
|
|
189
|
-
|
|
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).
|
|
191
|
-
|
|
192
|
-
### `useFieldArray`
|
|
193
|
-
|
|
194
|
-
Manage dynamic lists of fields:
|
|
195
|
-
|
|
196
|
-
```jsx
|
|
197
|
-
import {useFieldArray} from 'react-f0rm';
|
|
198
|
-
|
|
199
|
-
function Tags() {
|
|
200
|
-
const {fields, append, remove} = useFieldArray({name: 'tags'});
|
|
83
|
+
function CustomField({name}) {
|
|
84
|
+
const {inputProps, error} = useField({name});
|
|
201
85
|
return (
|
|
202
86
|
<div>
|
|
203
|
-
{
|
|
204
|
-
|
|
205
|
-
<Field name={['tags', index]} />
|
|
206
|
-
<button type="button" onClick={() => remove(index)}>Remove</button>
|
|
207
|
-
</div>
|
|
208
|
-
))}
|
|
209
|
-
<button type="button" onClick={() => append('')}>Add Tag</button>
|
|
87
|
+
<input {...inputProps} />
|
|
88
|
+
{error && <span role="alert" id={fieldErrorId(name)}>{error}</span>}
|
|
210
89
|
</div>
|
|
211
90
|
);
|
|
212
91
|
}
|
|
213
92
|
```
|
|
214
93
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
**Path syntax:** array access is bracket-only — `items[0]`, `items[0].name`. Dotted numeric segments (`items.0`) throw a `TypeError` whose message shows the bracket spelling to use; a quoted segment (`items["0"]`) explicitly names a string key instead of an index. Segment arrays (`['items', 0]`) remain the fully dynamic form.
|
|
218
|
-
|
|
219
|
-
Besides the movers (`append`, `prepend`, `insert`, `remove`, `swap`, `move`), two bulk operations are available:
|
|
220
|
-
|
|
221
|
-
```jsx
|
|
222
|
-
const {fields, replace, update} = useFieldArray({name: 'tags'});
|
|
223
|
-
|
|
224
|
-
replace(['a', 'b', 'c']); // full swap: every row id is regenerated (length may change)
|
|
225
|
-
update(1, 'B'); // overwrite one value, keeping that row's id — no key churn
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
`replace(values)` is the refetch shape — a server response replaces the whole list — while `update(index, value)` rewrites a single row in place.
|
|
229
|
-
|
|
230
|
-
Three more options cover the react-hook-form `useFieldArray` surface:
|
|
94
|
+
Or no hook at all — `form.register` is RHF's `register` contract (the element never re-renders; live state through `useValue`/`useError`):
|
|
231
95
|
|
|
232
96
|
```jsx
|
|
233
|
-
|
|
234
|
-
name
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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
|
-
|
|
245
|
-
### `useFieldArrayItem`
|
|
246
|
-
|
|
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:
|
|
248
|
-
|
|
249
|
-
```jsx
|
|
250
|
-
import {useFieldArray, useFieldArrayItem} from 'react-f0rm';
|
|
251
|
-
|
|
252
|
-
const Row = React.memo(function Row({id}) {
|
|
253
|
-
const item = useFieldArrayItem({name: 'tags', id});
|
|
254
|
-
return (
|
|
255
|
-
<div>
|
|
256
|
-
<input
|
|
257
|
-
value={item.value ?? ''}
|
|
258
|
-
onChange={e => item.setValue(e.target.value)}
|
|
259
|
-
/>
|
|
260
|
-
{item.error && <span>{item.error}</span>}
|
|
97
|
+
function DynamicFields({form}) {
|
|
98
|
+
return form.fields.map(name => (
|
|
99
|
+
<div key={name}>
|
|
100
|
+
<input {...form.register(name)} />
|
|
101
|
+
<FieldError name={name} />
|
|
261
102
|
</div>
|
|
262
|
-
);
|
|
263
|
-
});
|
|
264
|
-
|
|
265
|
-
function Tags() {
|
|
266
|
-
const {fields, append, remove} = useFieldArray({name: 'tags'});
|
|
267
|
-
return (
|
|
268
|
-
<div>
|
|
269
|
-
{fields.map(field => (
|
|
270
|
-
<div key={field.id}>
|
|
271
|
-
<Row id={field.id} />
|
|
272
|
-
<button type="button" onClick={() => remove(field.index)}>
|
|
273
|
-
Remove
|
|
274
|
-
</button>
|
|
275
|
-
</div>
|
|
276
|
-
))}
|
|
277
|
-
<button type="button" onClick={() => append('')}>
|
|
278
|
-
Add Tag
|
|
279
|
-
</button>
|
|
280
|
-
</div>
|
|
281
|
-
);
|
|
103
|
+
));
|
|
282
104
|
}
|
|
283
105
|
```
|
|
284
106
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
- a `useFieldArray({name})` must be mounted at the same path — it publishes the id table rows resolve against;
|
|
288
|
-
- the row component must be `React.memo` with stable props (`id`, optionally `form`): everything else comes from the hook, so the array component's own re-render cannot drag the rows along.
|
|
289
|
-
|
|
290
|
-
Rows whose index migrates — `remove`/`move`/`swap`/`insert` reshuffles — re-render by design: the row's path contains the index, exactly like TanStack Form's per-field api. `replace` regenerates every id, so every row remounts. The win is single-row edits staying single-row.
|
|
291
|
-
|
|
292
|
-
The hook returns `{value, setValue, errors, error, name, index, form}` — the `useField`-style shape plus `index` and `name` (the row's current path key, e.g. `["tags",0]`) for building nested fields. Value reads and writes live on the array layer — the same layer every `useFieldArray` operation touches — so `value`, `setValue` and `update`/`append`/… always agree with each other; editing through a leaf-path `useField({name: ['tags', i]})` writes a different layer and does not flow into `item.value`.
|
|
293
|
-
|
|
294
|
-
Without a paired `useFieldArray` the row is inert rather than broken: `index` is `-1`, `value` is `undefined`, and `setValue` is a no-op.
|
|
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
|
-
|
|
314
|
-
### `createFormContext`
|
|
315
|
-
|
|
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:
|
|
317
|
-
|
|
318
|
-
```tsx
|
|
319
|
-
import {createFormContext} from 'react-f0rm';
|
|
320
|
-
|
|
321
|
-
interface Values {
|
|
322
|
-
name: string;
|
|
323
|
-
email: string;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
const ProfileForm = createFormContext<Values>();
|
|
327
|
-
|
|
328
|
-
function NameField() {
|
|
329
|
-
// name is constrained to FieldPath<Values>; value is inferred as string
|
|
330
|
-
const {value, onChange} = ProfileForm.useField({name: 'name'});
|
|
331
|
-
return <input value={value} onChange={e => onChange(e.target.value)} />;
|
|
332
|
-
}
|
|
333
|
-
```
|
|
334
|
-
|
|
335
|
-
Each call returns `{context, FormProvider, useFormContext, useField, useFieldArray, useFieldArrayItem}` bound to a private React context — pass the form via `<ProfileForm.FormProvider form={form}>`, and providers from separate instances never see each other's forms.
|
|
336
|
-
|
|
337
|
-
The bundle also carries its raw React context, so `<Form>` can provide into it while keeping its full submit machinery — validation, submit handling, focus-on-error — instead of you wiring `<FormProvider>` + `handleSubmit` by hand:
|
|
338
|
-
|
|
339
|
-
```tsx
|
|
340
|
-
const ProfileForm = createFormContext<Values>();
|
|
341
|
-
|
|
342
|
-
<Form context={ProfileForm.context} form={form} onValidSubmit={save}>
|
|
343
|
-
<NameField /> {/* ProfileForm.useField resolves the form <Form> manages */}
|
|
344
|
-
<button type="submit">Save</button>
|
|
345
|
-
</Form>
|
|
346
|
-
```
|
|
347
|
-
|
|
348
|
-
The module-level `useFormContext()`/`useField` do not see that form — that is the isolation working.
|
|
349
|
-
|
|
350
|
-
## Controlled Forms
|
|
351
|
-
|
|
352
|
-
Pass a `values` prop to `<Form>` (or `values` to `useForm`) to drive the form from outside:
|
|
353
|
-
|
|
354
|
-
```jsx
|
|
355
|
-
<Form
|
|
356
|
-
values={selectedRecord}
|
|
357
|
-
onValidSubmit={values => save(values)}
|
|
358
|
-
>
|
|
359
|
-
<Field name="email" />
|
|
360
|
-
</Form>
|
|
361
|
-
```
|
|
362
|
-
|
|
363
|
-
Whenever the `values` reference changes, the new object is synced into the form: uncommitted user edits are discarded — master-detail semantics, where selecting another record replaces the draft — while touched flags and errors are kept. The sync guard is reference-first with a structural fallback: re-renders that pass the same `values` reference never re-sync, and neither does an inline literal whose content is structurally equal to what the form was last seeded from — only genuinely different content replaces the draft, so an unrelated re-render never interrupts what the user is typing.
|
|
364
|
-
|
|
365
|
-
## Disabled
|
|
366
|
-
|
|
367
|
-
Disable a whole form — during submission, while a record loads, or for read-only views:
|
|
368
|
-
|
|
369
|
-
```jsx
|
|
370
|
-
const form = useForm({disabled: isReadOnly});
|
|
371
|
-
|
|
372
|
-
// or toggle at runtime — every bound field re-renders:
|
|
373
|
-
setDisabled(form, true);
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
The flag is OR-ed into every bound field: `Field`, `Checkbox` and `Select` render their control disabled when either the form flag or their own `disabled` prop is true — a field cannot opt out of a disabled form. `useField` exposes the merged flag as `disabled`, kept live through the form's event core:
|
|
377
|
-
|
|
378
|
-
```jsx
|
|
379
|
-
const {disabled, value, onChange} = useField({name: 'email'});
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
## Submit Handlers
|
|
383
|
-
|
|
384
|
-
```jsx
|
|
385
|
-
<Form
|
|
386
|
-
initialValues={{email: ''}}
|
|
387
|
-
onValidSubmit={(values, e) => {
|
|
388
|
-
// Called after successful validation
|
|
389
|
-
saveToServer(values);
|
|
390
|
-
}}
|
|
391
|
-
onInvalidSubmit={(errors, values) => {
|
|
392
|
-
// Called when validation fails
|
|
393
|
-
// errors: [{path: 'email', type: 'custom', message: 'Invalid email'}]
|
|
394
|
-
console.error(errors);
|
|
395
|
-
}}
|
|
396
|
-
>
|
|
397
|
-
<Field name="email" />
|
|
398
|
-
<button>Submit</button>
|
|
399
|
-
</Form>
|
|
400
|
-
```
|
|
401
|
-
|
|
402
|
-
`onSubmit`/`onValidSubmit` only run once both native constraint validation (see [Accessibility](#accessibility)) and your custom validators pass.
|
|
403
|
-
|
|
404
|
-
### `handleSubmit`
|
|
405
|
-
|
|
406
|
-
The same submit flow is available as a standalone function — the headless counterpart of `<Form>`'s submit wiring, usable where there is no `<form>` element (React Native, toolbar buttons, …):
|
|
407
|
-
|
|
408
|
-
```jsx
|
|
409
|
-
import {useForm, handleSubmit} from 'react-f0rm';
|
|
410
|
-
|
|
411
|
-
function Profile({onSave}) {
|
|
412
|
-
const form = useForm({initialValues: {email: ''}});
|
|
413
|
-
const submit = handleSubmit(form, {
|
|
414
|
-
onSubmit: values => onSave(values), // runs first on success
|
|
415
|
-
onValidSubmit: values => console.log(values), // then this
|
|
416
|
-
onInvalidSubmit: (errors, values) => console.error(errors)
|
|
417
|
-
});
|
|
418
|
-
return <Button title="Save" onPress={submit} />;
|
|
419
|
-
}
|
|
420
|
-
```
|
|
421
|
-
|
|
422
|
-
All callbacks are optional — a missing one is simply skipped. The returned handler runs the full submit state machine (`isSubmitting`, `submitCount`, `isSubmitSuccessful`) around native constraint validation (skipped when the event target has no `checkValidity`) and your validators, and can be invoked with or without an event object.
|
|
423
|
-
|
|
424
|
-
`onInvalidSubmit` receives an array of `{path, type, message}` entries: custom validation failures carry dotted paths with your validator's type (`'custom'` for plain strings, `'standard'` for the Standard Schema adapter), and native constraint failures carry `type: 'native'` — `path` is the dotted field path and `message` comes from the browser's `validationMessage`. Native failures are read from the DOM and never enter the form's error state.
|
|
425
|
-
|
|
426
|
-
### Submit button state
|
|
427
|
-
|
|
428
|
-
`useCanSubmit(form)` is the single flag a submit button's `disabled` prop wants — `!isSubmitting && !hasErrors`:
|
|
429
|
-
|
|
430
|
-
```jsx
|
|
431
|
-
import {useForm, useCanSubmit, handleSubmit} from 'react-f0rm';
|
|
432
|
-
|
|
433
|
-
function Profile({onSave}) {
|
|
434
|
-
const form = useForm({initialValues: {email: ''}});
|
|
435
|
-
const canSubmit = useCanSubmit(form);
|
|
436
|
-
return (
|
|
437
|
-
<button disabled={!canSubmit} onClick={handleSubmit(form, {onSubmit: onSave})}>
|
|
438
|
-
Save
|
|
439
|
-
</button>
|
|
440
|
-
);
|
|
441
|
-
}
|
|
442
|
-
```
|
|
443
|
-
|
|
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.
|
|
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
|
-
|
|
459
|
-
### Focusing the first error
|
|
460
|
-
|
|
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.
|
|
462
|
-
|
|
463
|
-
The same channel is exposed as an imperative API:
|
|
464
|
-
|
|
465
|
-
```jsx
|
|
466
|
-
import {setFocus} from 'react-f0rm';
|
|
467
|
-
|
|
468
|
-
setFocus(form, 'email'); // focus the bound field's element
|
|
469
|
-
setFocus(form, 'user.name', {shouldSelect: true}); // focus and select its text
|
|
470
|
-
```
|
|
471
|
-
|
|
472
|
-
`setFocus` rides the `'focusError'` event, so it is a silent no-op when the field is unmounted or nothing subscribes — unknown names never throw.
|
|
473
|
-
|
|
474
|
-
## Validation
|
|
475
|
-
|
|
476
|
-
### Validation modes
|
|
477
|
-
|
|
478
|
-
`mode` controls when field validators run; `reValidateMode` controls when a field is re-validated once it already has an error — it supplements `mode` in every mode:
|
|
479
|
-
|
|
480
|
-
| Option | Values | Default |
|
|
481
|
-
|---|---|---|
|
|
482
|
-
| `mode` | `'onSubmit'` \| `'onBlur'` \| `'onChange'` \| `'onTouched'` \| `'all'` | `'onSubmit'` |
|
|
483
|
-
| `reValidateMode` | `'onChange'` \| `'onBlur'` \| `'onSubmit'` | `'onChange'` |
|
|
484
|
-
|
|
485
|
-
- `'onSubmit'` — validate only on submit.
|
|
486
|
-
- `'onBlur'` — validate when the field loses focus.
|
|
487
|
-
- `'onChange'` — validate on every change.
|
|
488
|
-
- `'onTouched'` — validate on the first blur, then on every change.
|
|
489
|
-
- `'all'` — validate on both change and blur.
|
|
490
|
-
|
|
491
|
-
```jsx
|
|
492
|
-
import {createForm} from 'react-f0rm';
|
|
493
|
-
|
|
494
|
-
const form = createForm({
|
|
495
|
-
initialValues: {email: ''},
|
|
496
|
-
mode: 'onBlur', // validate on blur…
|
|
497
|
-
reValidateMode: 'onChange' // …then re-validate on every change once errored
|
|
498
|
-
});
|
|
499
|
-
```
|
|
500
|
-
|
|
501
|
-
#### Per-field mode override
|
|
502
|
-
|
|
503
|
-
Sometimes one field deserves a different schedule than the rest of the form — a signup form that validates on submit, except the email field whose check should fire as soon as the user leaves the input. Any field can declare its own `mode`: it replaces the form-level `mode` for that field only, while every other field keeps the form's timing.
|
|
504
|
-
|
|
505
|
-
```jsx
|
|
506
|
-
import {Form, Field, useForm} from 'react-f0rm';
|
|
507
|
-
|
|
508
|
-
function Register() {
|
|
509
|
-
// Form default: validate on submit.
|
|
510
|
-
const form = useForm({initialValues: {email: '', bio: ''}});
|
|
511
|
-
|
|
512
|
-
return (
|
|
513
|
-
<Form form={form}>
|
|
514
|
-
{/* This field alone validates on blur... */}
|
|
515
|
-
<Field name="email" mode="onBlur" validate={checkEmail} />
|
|
516
|
-
{/* ...while every other field waits for submit. */}
|
|
517
|
-
<Field name="bio" />
|
|
518
|
-
</Form>
|
|
519
|
-
);
|
|
520
|
-
}
|
|
521
|
-
```
|
|
522
|
-
|
|
523
|
-
The same option exists on `useField` (and `Checkbox` / `Select`):
|
|
524
|
-
|
|
525
|
-
```jsx
|
|
526
|
-
const email = useField({name: 'email', mode: 'onBlur', validate: checkEmail});
|
|
527
|
-
```
|
|
528
|
-
|
|
529
|
-
- Accepted values are the same `ValidationMode` union as the form's `mode`; omit it and the field follows `form.mode` exactly as before.
|
|
530
|
-
- Precedence is per field: `field.mode ?? form.mode`. A field cannot change another field's timing, and declaring `mode: 'onSubmit'` opts a field out of an `'onChange'` form.
|
|
531
|
-
- `reValidateMode` stays form-level for every field: once a field has an error (after a failed submit, say), re-validation follows the form's `reValidateMode` regardless of the field's own `mode` — a `mode: 'onBlur'` field with the default `reValidateMode: 'onChange'` still re-validates on every keystroke while errored.
|
|
532
|
-
- Manual `trigger` and submit validation are unaffected — they always run the field's validators regardless of any mode.
|
|
533
|
-
|
|
534
|
-
### Triggering validation manually
|
|
535
|
-
|
|
536
|
-
`trigger` runs field validators on demand. Without a name it runs every registered validator; a single name — or an array of names — narrows it to those fields:
|
|
537
|
-
|
|
538
|
-
```jsx
|
|
539
|
-
import {trigger} from 'react-f0rm';
|
|
540
|
-
|
|
541
|
-
trigger(form); // every registered field validator
|
|
542
|
-
trigger(form, 'email'); // one field
|
|
543
|
-
trigger(form, ['user.name', 'user.email']); // several
|
|
544
|
-
```
|
|
545
|
-
|
|
546
|
-
`trigger` returns a promise that waits for the triggered validation to settle — async validators and pending debounce windows included — so errors have already landed in `form.errors` when it resolves. It never rejects: landing errors is the expected outcome here, not a failure. It resolves `true` when the triggered scope is error-free, `false` otherwise:
|
|
547
|
-
|
|
548
|
-
```jsx
|
|
549
|
-
if (await trigger(form, 'email')) {
|
|
550
|
-
proceed(); // 'email' is now guaranteed error-free
|
|
551
|
-
}
|
|
552
|
-
```
|
|
553
|
-
|
|
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.
|
|
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
|
-
|
|
562
|
-
### Async validation
|
|
563
|
-
|
|
564
|
-
Async validators are first-class. Two knobs keep them cheap and race-free:
|
|
565
|
-
|
|
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.
|
|
569
|
-
|
|
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:
|
|
571
|
-
|
|
572
|
-
```jsx
|
|
573
|
-
<Field
|
|
574
|
-
name="email"
|
|
575
|
-
validateDebounce={300}
|
|
576
|
-
validate={async (value, {signal}) => {
|
|
577
|
-
const res = await fetch(`/api/check-email?email=${encodeURIComponent(value)}`, {signal});
|
|
578
|
-
const {taken} = await res.json();
|
|
579
|
-
if (taken) return {type: 'taken', message: 'Email already registered'};
|
|
580
|
-
}}
|
|
581
|
-
/>
|
|
582
|
-
```
|
|
583
|
-
|
|
584
|
-
Stale results are dropped independently of the signal — validators that ignore it stay correct — but passing it to `fetch` (or `AbortSignal.timeout`, timers, …) also cancels the network work itself.
|
|
585
|
-
|
|
586
|
-
### Multiple errors per field
|
|
587
|
-
|
|
588
|
-
Every field stores an ordered `FieldError[]`, not a single error. The first entry is what `error`/`errorObject`/`getError` expose; readers that want all of them use `getFieldErrors(form, name)` or `useFieldErrors(form, name)`:
|
|
589
|
-
|
|
590
|
-
```jsx
|
|
591
|
-
import {getFieldErrors, useFieldErrors, setError} from 'react-f0rm';
|
|
592
|
-
|
|
593
|
-
const all = getFieldErrors(form, 'password');
|
|
594
|
-
// [{type: 'min', message: 'Too short'}, {type: 'pattern', message: 'Needs a digit'}]
|
|
595
|
-
|
|
596
|
-
setError(form, 'password', [
|
|
597
|
-
{type: 'min', message: 'Too short'},
|
|
598
|
-
{type: 'pattern', message: 'Needs a digit'}
|
|
599
|
-
]);
|
|
600
|
-
```
|
|
601
|
-
|
|
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.
|
|
603
|
-
|
|
604
|
-
### `setValue` options
|
|
605
|
-
|
|
606
|
-
The fourth argument to `setValue` opts into side effects. `shouldValidate`/`shouldTouch` default to `false`; omitting the object keeps the plain set-value behavior:
|
|
607
|
-
|
|
608
|
-
```jsx
|
|
609
|
-
import {setValue} from 'react-f0rm';
|
|
610
|
-
|
|
611
|
-
setValue(form, 'email', 'a@b.com', {
|
|
612
|
-
shouldValidate: true, // run the field's registered validator after the value lands
|
|
613
|
-
shouldTouch: true, // mark the field as touched
|
|
614
|
-
shouldDirty: false // land the value as a commit: it becomes the field's dirty baseline
|
|
615
|
-
});
|
|
616
|
-
```
|
|
617
|
-
|
|
618
|
-
Dirty state is derived, not marked: a field is dirty while its live value differs from `initialValues` (reverting to the initial value makes it clean again). That makes `shouldDirty` a one-sided flag. `shouldDirty: false` declares this write a **commit instead of an edit** — the written value becomes that field's dirty-comparison baseline, so `getDirtyFields`/`isDirty`/`getFieldState().isDirty` read the field as clean immediately, and a later write dirties it only by differing from the new baseline:
|
|
619
|
-
|
|
620
|
-
```jsx
|
|
621
|
-
setValue(form, 'email', 'normalized@x.com', {shouldDirty: false});
|
|
622
|
-
getDirtyFields(form); // {} — the normalization is not a user edit
|
|
623
|
-
|
|
624
|
-
setValue(form, 'email', 'normalized@x.com'); // still clean: equal to the baseline
|
|
625
|
-
setValue(form, 'email', 'a@b.com'); // dirty: differs from it
|
|
626
|
-
```
|
|
627
|
-
|
|
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.
|
|
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:
|
|
107
|
+
Schemas go straight into `validate`:
|
|
631
108
|
|
|
632
109
|
```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
|
-
|
|
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.
|
|
640
|
-
|
|
641
|
-
### Writing as a user change (`changeValue`)
|
|
642
|
-
|
|
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`.
|
|
644
|
-
|
|
645
|
-
```jsx
|
|
646
|
-
import {changeValue} from 'react-f0rm';
|
|
647
|
-
|
|
648
|
-
// An onSubmit form with the default reValidateMode 'onChange': quiet
|
|
649
|
-
// while the field has no error, re-validates once it does — same as typing.
|
|
650
|
-
changeValue(form, 'email', 'a@b.com');
|
|
651
|
-
```
|
|
652
|
-
|
|
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`.
|
|
654
|
-
|
|
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:
|
|
656
|
-
|
|
657
|
-
```jsx
|
|
658
|
-
changeValue(form, 'email', 'normalized@x.com', {shouldDirty: false});
|
|
659
|
-
```
|
|
660
|
-
|
|
661
|
-
### Field-level validation
|
|
662
|
-
|
|
663
|
-
Pass a `validate` function to `Field` or `useField`. Return an error string, a `FieldError` object or `undefined` — sync or async:
|
|
664
|
-
|
|
665
|
-
```jsx
|
|
666
|
-
<Field
|
|
667
|
-
name="email"
|
|
668
|
-
validate={value => {
|
|
669
|
-
if (!value.includes('@')) return 'Invalid email';
|
|
670
|
-
}}
|
|
671
|
-
/>
|
|
672
|
-
```
|
|
673
|
-
|
|
674
|
-
### Rules
|
|
675
|
-
|
|
676
|
-
For declarative constraints, pass `rules` to `Field` (or any bound component — `Checkbox`, `Select` — or `useField`). Rule failures land in the form's error state as `FieldError`s (`type` is the rule name) carrying your message, so any design system can render them uniformly instead of the browser's validity bubble:
|
|
677
|
-
|
|
678
|
-
```jsx
|
|
679
|
-
<Field
|
|
680
|
-
name="age"
|
|
681
|
-
rules={{
|
|
682
|
-
required: 'Age is required',
|
|
683
|
-
min: 18,
|
|
684
|
-
messages: {min: 'Must be an adult'}
|
|
685
|
-
}}
|
|
686
|
-
/>
|
|
687
|
-
```
|
|
688
|
-
|
|
689
|
-
| Rule | Value | Fails when | Default message |
|
|
690
|
-
|---|---|---|---|
|
|
691
|
-
| `required` | `string \| true` | value is `''`, `undefined` or `null` (`0` and `false` count as filled) | `'This field is required'` |
|
|
692
|
-
| `min` | `number` | `Number(value) < min` — values converting to `NaN` skip the rule | `` `Must be at least ${min}` `` |
|
|
693
|
-
| `max` | `number` | `Number(value) > max` — `NaN` skips | `` `Must be at most ${max}` `` |
|
|
694
|
-
| `minLength` | `number` | a string value is shorter — non-strings skip | `` `Must be at least ${n} characters` `` |
|
|
695
|
-
| `maxLength` | `number` | a string value is longer — non-strings skip | `` `Must be at most ${n} characters` `` |
|
|
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
|
-
```
|
|
713
|
-
|
|
714
|
-
The optional top-level `messages` record overrides messages per rule type (`min`, `max`, `minLength`, `maxLength`, `pattern`) — useful for centralizing or localizing them.
|
|
715
|
-
|
|
716
|
-
Semantics:
|
|
717
|
-
|
|
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.
|
|
720
|
-
- Every other failing rule collects into one ordered `FieldError[]` (see [Multiple errors per field](#multiple-errors-per-field)).
|
|
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.
|
|
724
|
-
|
|
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.
|
|
726
|
-
|
|
727
|
-
### Form-level validation
|
|
728
|
-
|
|
729
|
-
Pass a `validate` function to `createForm`. It receives all values and returns a record of errors. Nested objects are flattened recursively — `{user: {name: 'Required'}}` sets the error at `user.name` — and plain flat results keep working:
|
|
730
|
-
|
|
731
|
-
```jsx
|
|
732
|
-
import {createForm} from 'react-f0rm';
|
|
733
|
-
|
|
734
|
-
const form = createForm({
|
|
735
|
-
initialValues: {password: '', confirm: ''},
|
|
736
|
-
validate: values => {
|
|
737
|
-
if (values.password !== values.confirm) {
|
|
738
|
-
return {confirm: 'Passwords do not match'};
|
|
739
|
-
}
|
|
740
|
-
},
|
|
741
|
-
});
|
|
742
|
-
```
|
|
743
|
-
|
|
744
|
-
The validate function may be async (it is awaited), and its optional second argument carries `{form, signal}` — the same contract as field validators' `meta`. Add `validateDebounce` (milliseconds) to give the whole-form validate the per-field window contract: kicks from `trigger`/submit inside the window merge into one run reading the values current when the window closes, and while the timer is pending the form counts as *validating*, so `trigger` and submit wait the window out instead of racing it:
|
|
745
|
-
|
|
746
|
-
```jsx
|
|
747
|
-
const form = useForm({
|
|
748
|
-
validate: async (values, {signal}) => {
|
|
749
|
-
const res = await fetch('/api/validate', {
|
|
750
|
-
method: 'POST',
|
|
751
|
-
body: JSON.stringify(values),
|
|
752
|
-
signal
|
|
753
|
-
});
|
|
754
|
-
const {errors} = await res.json();
|
|
755
|
-
return errors; // nested error record, flattened like above
|
|
756
|
-
},
|
|
757
|
-
validateDebounce: 300
|
|
758
|
-
});
|
|
759
|
-
```
|
|
760
|
-
|
|
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.
|
|
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
|
-
|
|
778
|
-
#### Re-running on dependent field changes (`validateDeps`)
|
|
779
|
-
|
|
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`**:
|
|
781
|
-
|
|
782
|
-
```jsx
|
|
783
|
-
const form = useForm({
|
|
784
|
-
initialValues: {password: '', confirm: ''},
|
|
785
|
-
validate: values =>
|
|
786
|
-
values.password !== values.confirm
|
|
787
|
-
? {confirm: 'Passwords do not match'}
|
|
788
|
-
: {},
|
|
789
|
-
validateDeps: ['password']
|
|
790
|
-
});
|
|
791
|
-
```
|
|
792
|
-
|
|
793
|
-
Now the submit-then-fix flow works: submit lands the mismatch on `confirm`, editing `password` re-runs the validate, and the passing round makes the error disappear. The re-run timing rides the same mode matrix as any field validator, evaluated against the changed field's effective `mode` (per-field override included) and the form's `reValidateMode`:
|
|
794
|
-
|
|
795
|
-
| Situation | Dep change re-runs the form validate? |
|
|
796
|
-
|---|---|
|
|
797
|
-
| `mode: 'onChange'` / `'all'` (form or the dep field) | yes, error state or not |
|
|
798
|
-
| `mode: 'onTouched'`, dep field touched | yes |
|
|
799
|
-
| otherwise, the last round's error is live **and** `reValidateMode: 'onChange'` (default) | yes — the submit-then-fix flow |
|
|
800
|
-
| `reValidateMode: 'onBlur'` / `'onSubmit'` | no — a change is not a blur; re-runs wait for their own trigger |
|
|
801
|
-
|
|
802
|
-
Details that fall out of the plumbing:
|
|
803
|
-
|
|
804
|
-
- **User changes only.** The kick rides the mounted field's own change pipeline, so typing and `changeValue` (component-library bridges) both fire it, while programmatic `setValue` does not — exactly like field validators. A dep path with no mounted field never re-runs the validate.
|
|
805
|
-
- **Round-scoped error ownership.** Opting in changes what a re-run may clear: each round first drops the errors the *previous round* wrote, then lands its own result — so a passing re-run clears the stale mismatch. Errors the round never wrote (field validators', `setServerErrors`, manual `setError`) survive it, and a foreign write onto a round-owned path takes the key out of the round's ownership.
|
|
806
|
-
- **`validateDebounce` applies.** Dep-change kicks are ordinary kicks: they merge inside the debounce window like `trigger`/submit kicks do.
|
|
807
|
-
- Forms that don't set `validateDeps` keep the historical behavior untouched — the form validate runs on `trigger`/submit only, and re-runs never clear earlier errors.
|
|
808
|
-
|
|
809
|
-
TanStack Form's counterpart is `onChangeListenTo` (v1) / validator `triggers` (v2 alpha); both re-run a validator when listed fields change. react-f0rm keeps the declaration at the form level (the validate belongs to the form) and gates the re-run by the library's own `mode`/`reValidateMode` semantics instead of adding an always-on listener.
|
|
810
|
-
|
|
811
|
-
#### Field-to-field linkage (`validateDeps` on `useField`)
|
|
812
|
-
|
|
813
|
-
The same declaration exists per field: `validateDeps` on `useField` lists the **other** fields whose user changes re-run **this field's validator** — the field-level shape of the option above, for cross-field rules you want as field errors (queryable via `getError`, renderable by `renderError`) without a form-level validate:
|
|
814
|
-
|
|
815
|
-
```jsx
|
|
816
|
-
const form = useForm({
|
|
817
|
-
initialValues: {password: '', passwordConfirm: ''}
|
|
818
|
-
});
|
|
819
|
-
|
|
820
|
-
function PasswordConfirmField() {
|
|
821
|
-
const {value, onChange, error} = useField({
|
|
822
|
-
form,
|
|
823
|
-
name: 'passwordConfirm',
|
|
824
|
-
validate: v => (v === getValue(form, 'password') ? undefined : 'Passwords do not match'),
|
|
825
|
-
validateDeps: ['password']
|
|
826
|
-
});
|
|
827
|
-
// ...
|
|
828
|
-
}
|
|
829
|
-
```
|
|
830
|
-
|
|
831
|
-
The re-run semantics mirror the form-level option exactly, because it rides the same channel — the changed field's own onChange pipeline:
|
|
832
|
-
|
|
833
|
-
| Situation | Dep change re-runs this field's validator? |
|
|
834
|
-
|---|---|
|
|
835
|
-
| `mode: 'onChange'` / `'all'` (form or the dep field) | yes, error state or not |
|
|
836
|
-
| `mode: 'onTouched'`, dep field touched | yes |
|
|
837
|
-
| otherwise, this field shows an error **and** `reValidateMode: 'onChange'` (default) | yes — the submit-then-fix flow |
|
|
838
|
-
| `reValidateMode: 'onBlur'` / `'onSubmit'` | no — re-runs wait for their own trigger |
|
|
839
|
-
|
|
840
|
-
- **User changes only.** Typing and `changeValue` fire it; programmatic `setValue` does not. A dep path with no mounted field never re-runs the validator.
|
|
841
|
-
- **A passing re-run clears the error.** A field validator owns its whole error key (every kick's result replaces the previous list), so the submit-then-fix flow needs no footprint bookkeeping: edit `password` until it matches and the confirm error disappears.
|
|
842
|
-
- **`validateDebounce` applies** — the re-run is an ordinary kick of this field's validator, debounce window included.
|
|
843
|
-
- Listing the field's own path is a no-op (its own change already validates it), and unmounting the dependent field drops the linkage.
|
|
844
|
-
|
|
845
|
-
### Schema validation
|
|
846
|
-
|
|
847
|
-
Any library implementing [Standard Schema v1](https://standardschema.dev) — zod v3.24+/v4, valibot v1, arktype and more — works through one adapter, imported from its own tree-shakeable entry point:
|
|
848
|
-
|
|
849
|
-
```jsx
|
|
850
|
-
import {Form, Field, createForm} from 'react-f0rm';
|
|
851
|
-
import {
|
|
852
|
-
standardSchemaFormValidator,
|
|
853
|
-
standardSchemaResolver
|
|
854
|
-
} from 'react-f0rm/resolvers/standard-schema';
|
|
855
110
|
import {z} from 'zod';
|
|
856
111
|
|
|
857
|
-
const schema = z.object({
|
|
858
|
-
email: z.string().email(),
|
|
859
|
-
password: z.string().min(8)
|
|
860
|
-
});
|
|
861
|
-
|
|
862
|
-
// Form-level: validate the whole values object; issue paths map to
|
|
863
|
-
// field errors automatically, issues without a path land on `_form`
|
|
864
|
-
const form = createForm({
|
|
865
|
-
validate: standardSchemaFormValidator(schema)
|
|
866
|
-
});
|
|
867
|
-
|
|
868
|
-
// Field-level: validate a single value
|
|
869
|
-
<Field name="email" validate={standardSchemaResolver(z.string().email())} />
|
|
870
|
-
```
|
|
871
|
-
|
|
872
|
-
Schema errors come back as `{type: 'standard', message}`.
|
|
873
|
-
|
|
874
|
-
On success the adapter returns the schema's parsed output, which the form stores as its `parsedValues` baseline: `getValues()` and submit callbacks (`onSubmit`/`onValidSubmit`) read coerced/transformed values — `z.coerce.number()` hands back a real `number`, not the raw string. The baseline sits between `initialValues` and live edits, so fields the user changes afterwards still win, and dirty state keeps comparing live edits against `initialValues` only — parsing never marks a field dirty. `reset()` and `setInitialValues()` clear the baseline.
|
|
875
|
-
|
|
876
|
-
#### Schema defaults
|
|
877
|
-
|
|
878
|
-
**Standard Schema v1 has no default-value metadata.** The interface carries types and `validate` and nothing else — whether a field declares a default, and how to read it, is vendor territory: zod v3.24 exposes `.getDefault()` per field, zod v4 wraps defaulted fields in a `ZodDefault` whose `.def.defaultValue` is a de-facto-public field rather than a documented accessor, valibot ships a `getDefault` util. None of it is reachable through the standard surface, and react-f0rm reads schemas only through `~standard.validate` — probing `schema.shape`/`.def` internals per vendor is exactly the adapter-per-library tree this library refuses to grow. So `defaultValues` derived from a schema is deliberately **not** a library feature: pass `initialValues` explicitly.
|
|
879
|
-
|
|
880
|
-
What you do get for free: defaults flow through `validate`. A schema's parsed output contains every declared default, so after the first successful validation the `parsedValues` baseline already serves them — `getValues()` reads `z.string().default('anon')` fields as `'anon'` without any seeding. The gap is only the render before the first validation round, and two recipes close it user-side:
|
|
881
|
-
|
|
882
|
-
```jsx
|
|
883
|
-
// 1. Vendor-neutral: one parse of an empty object materializes every
|
|
884
|
-
// default the schema declares (nested ones included).
|
|
885
|
-
const result = schema['~standard'].validate({});
|
|
886
|
-
const initialValues = result.issues ? {} : result.value;
|
|
887
|
-
|
|
888
|
-
const form = useForm({initialValues, validate: standardSchemaFormValidator(schema)});
|
|
889
|
-
```
|
|
890
|
-
|
|
891
|
-
The empty parse succeeds only where defaults cover everything; a required field without a default fails it, and `{}` is the honest seed in that case. For per-field extraction instead of a whole-object parse, do it through the vendor's own API — zod v4:
|
|
892
|
-
|
|
893
|
-
```jsx
|
|
894
|
-
// 2. zod v4: ZodDefault wrappers expose their default on .def
|
|
895
|
-
const defaultValues = Object.fromEntries(
|
|
896
|
-
Object.entries(schema.shape).map(([key, field]) => [
|
|
897
|
-
key,
|
|
898
|
-
field.def?.type === 'default' ? field.def.defaultValue : undefined
|
|
899
|
-
])
|
|
900
|
-
);
|
|
901
|
-
```
|
|
902
|
-
|
|
903
|
-
(zod v3.24: the same loop calling `field.getDefault()`. That this loop is version-specific is the point — it is your schema and your vendor, not the form library's, contract to maintain.)
|
|
904
|
-
|
|
905
|
-
### Delaying error display
|
|
906
|
-
|
|
907
|
-
`delayError` (milliseconds) holds a newly appearing error back from the render for a short window — users typing through a field are not interrupted by an error the next keystroke may already fix:
|
|
908
|
-
|
|
909
|
-
```jsx
|
|
910
|
-
<Field name="username" rules={{minLength: 3}} delayError={300} />
|
|
911
|
-
```
|
|
912
|
-
|
|
913
|
-
The delay is render-layer only: `error`/`errorObject`/`errors` from `useField` (and everything `Field` derives from them — `aria-invalid`, `renderError`) stay `undefined`/empty until the window passes. The form's error state is never delayed — `trigger`, submit and `getError(form, name)` read the error immediately, unlike react-hook-form's formState-level delay. An error that clears inside the window never shows at all; once an error is visible, later changes (a new message, entries added or removed) apply immediately — only the none → some transition waits.
|
|
914
|
-
|
|
915
|
-
## Dirty & Touched Fields
|
|
916
|
-
|
|
917
|
-
```jsx
|
|
918
|
-
import {useDirtyFields, useTouchedFields} from 'react-f0rm';
|
|
919
|
-
|
|
920
|
-
function FormStatus({form}) {
|
|
921
|
-
const dirtyFields = useDirtyFields(form); // {'user.name': true, 'tags.0': true}
|
|
922
|
-
const touched = useTouchedFields(form); // ['user.name', 'tags.0']
|
|
923
|
-
return (
|
|
924
|
-
<p>{Object.keys(dirtyFields).length} dirty, {touched.length} touched</p>
|
|
925
|
-
);
|
|
926
|
-
}
|
|
927
|
-
```
|
|
928
|
-
|
|
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.
|
|
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
|
-
|
|
933
|
-
### Seeding new initial values
|
|
934
|
-
|
|
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:
|
|
936
|
-
|
|
937
|
-
```jsx
|
|
938
|
-
const article = useData<Article>() ?? undefined;
|
|
939
|
-
// No useMemo needed: a new object per render with equal content never
|
|
940
|
-
// clears what the user typed; switching to another article re-seeds.
|
|
941
|
-
const form = useForm({initialValues: articleToValues(article)});
|
|
942
|
-
```
|
|
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
112
|
const form = useForm({
|
|
950
|
-
initialValues:
|
|
113
|
+
initialValues: {email: '', password: ''},
|
|
114
|
+
validate: z.object({
|
|
115
|
+
email: z.string().email(),
|
|
116
|
+
password: z.string().min(8)
|
|
117
|
+
}) // no resolver import; TValues infers from the schema
|
|
951
118
|
});
|
|
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
|
-
|
|
964
|
-
### Resetting
|
|
965
|
-
|
|
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:
|
|
967
|
-
|
|
968
|
-
```jsx
|
|
969
|
-
import {reset} from 'react-f0rm';
|
|
970
|
-
|
|
971
|
-
reset(form); // back to the current initialValues
|
|
972
|
-
reset(form, freshRecord); // full reset to the new baseline
|
|
973
|
-
reset(form, freshRecord, {keepDirtyValues: true}); // dirty drafts survive
|
|
974
|
-
reset(form, undefined, {keepTouched: true}); // reset, keep touched flags
|
|
975
|
-
```
|
|
976
|
-
|
|
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):
|
|
978
|
-
|
|
979
|
-
```jsx
|
|
980
|
-
const {data} = useQuery(['user', id], () => fetchUser(id));
|
|
981
|
-
// data changed (refetch, different user) — replace the draft,
|
|
982
|
-
// but never clobber fields the user is mid-edit on
|
|
983
|
-
useEffect(() => {
|
|
984
|
-
if (data) reset(form, data, {keepDirtyValues: true});
|
|
985
|
-
}, [data]);
|
|
986
|
-
```
|
|
987
|
-
|
|
988
|
-
The other flags — `keepTouched`, `keepErrors`, `keepIsSubmitted`, `keepSubmitCount`, `keepIsSubmitting` — all default to `false`; omitting the object keeps the plain full-reset behavior.
|
|
989
|
-
|
|
990
|
-
### Resetting a single field
|
|
991
|
-
|
|
992
|
-
`resetField(form, name, options?)` resets one field and leaves the rest of the form alone: the field's live value is dropped (reads fall back to `initialValues` — when a schema's `parsedValues` baseline exists, its path is removed so the coerced output stops shadowing the initial value), and the field's touched flag and errors are cleared:
|
|
993
|
-
|
|
994
|
-
```jsx
|
|
995
|
-
import {resetField, getFieldState} from 'react-f0rm';
|
|
996
|
-
|
|
997
|
-
resetField(form, 'email'); // back to initialValues
|
|
998
|
-
resetField(form, 'email', {keepTouched: true}); // keep the touched flag
|
|
999
|
-
resetField(form, 'email', {value: ''}); // explicit value, no fallback
|
|
1000
|
-
```
|
|
1001
|
-
|
|
1002
|
-
| Option | Default | Effect |
|
|
1003
|
-
| ------------- | ------- | ------------------------------------------------------------- |
|
|
1004
|
-
| `keepTouched` | `false` | Keep the field's touched flag |
|
|
1005
|
-
| `keepErrors` | `false` | Keep the field's errors |
|
|
1006
|
-
| `value` | — | Explicit post-reset value; never falls back to `initialValues` |
|
|
1007
|
-
|
|
1008
|
-
Its read-side sibling `getFieldState(form, name)` returns one field's aggregated state — `{value, error, errors, isDirty, isTouched, isValidating}` — where `isDirty` applies the same rule as `getDirtyFields` (a live value differing from `initialValues`; parsing never counts) and `errors` is the stored array shared with `getFieldErrors`, so treat it as read-only:
|
|
1009
|
-
|
|
1010
|
-
```jsx
|
|
1011
|
-
const {value, error, isDirty} = getFieldState(form, 'email');
|
|
1012
|
-
```
|
|
1013
|
-
|
|
1014
|
-
## Accessibility
|
|
1015
|
-
|
|
1016
|
-
Bound fields (`Field`, `Checkbox`, `Select`) wire the error chain automatically: whenever the field has an error, the control gets `aria-invalid="true"` and its `aria-describedby` gains `fieldErrorId(name)` — the id the error message element is expected to carry. `fieldErrorId` is exported, so a custom error component only needs to render that id with `role="alert"` to complete the chain for screen readers:
|
|
1017
|
-
|
|
1018
|
-
```jsx
|
|
1019
|
-
import {useFormContext, useError, fieldErrorId} from 'react-f0rm';
|
|
1020
|
-
|
|
1021
|
-
function FieldMessage({name}) {
|
|
1022
|
-
const form = useFormContext();
|
|
1023
|
-
const error = useError(form, name);
|
|
1024
|
-
return error ? (
|
|
1025
|
-
<span id={fieldErrorId(name)} role="alert" className="field-error">
|
|
1026
|
-
{error}
|
|
1027
|
-
</span>
|
|
1028
|
-
) : null;
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
<Field name="email" />
|
|
1032
|
-
<FieldMessage name="email" />
|
|
1033
|
-
```
|
|
1034
|
-
|
|
1035
|
-
For the built-in path, provide a `renderError(error, id)` function instead: `Field` renders `<span id={id} role="alert">{renderError(error, id)}</span>` next to the input — same id, same wiring, no extra component:
|
|
1036
|
-
|
|
1037
|
-
```jsx
|
|
1038
|
-
<Field
|
|
1039
|
-
name="email"
|
|
1040
|
-
renderError={error => <em>{error}</em>}
|
|
1041
|
-
/>
|
|
1042
|
-
```
|
|
1043
|
-
|
|
1044
|
-
A user-provided `aria-describedby` survives: on error, the field's id is appended after yours (`"hint email"`). Without an error, no `aria-describedby` is added.
|
|
1045
|
-
|
|
1046
|
-
Native constraint validation (`required`, `type=email`, `minLength`, …) gates submission: `<Form>` runs the browser's `checkValidity()` before custom validators, and failing constraints surface as native validation bubbles via `reportValidity()`.
|
|
1047
|
-
|
|
1048
|
-
## Server-side errors
|
|
1049
|
-
|
|
1050
|
-
Server 422s land on the same channel client-side validation uses. `setServerErrors(form, errors)` takes the flat `Record<string, string | string[]>` shape REST APIs commonly return — RealWorld's `422 {errors: {email: ['has already been taken']}}` needs no hand-rolled `Object.entries` + `setError` loop — and stores each entry as the field's error(s) with `type: 'server'`:
|
|
1051
|
-
|
|
1052
|
-
```jsx
|
|
1053
|
-
import {setServerErrors} from 'react-f0rm';
|
|
1054
|
-
|
|
1055
|
-
async function onSubmit(values) {
|
|
1056
|
-
try {
|
|
1057
|
-
await api.post('/users', {user: values});
|
|
1058
|
-
} catch (e) {
|
|
1059
|
-
// e.data.errors: {email: ['has already been taken'], ...}
|
|
1060
|
-
setServerErrors(form, e.data.errors);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
```
|
|
1064
|
-
|
|
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.
|
|
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
119
|
```
|
|
1094
120
|
|
|
1095
|
-
|
|
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
|
-
|
|
1099
|
-
## TypeScript
|
|
121
|
+
Try the components without writing an app: `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.
|
|
1100
122
|
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
```tsx
|
|
1104
|
-
import {FieldPath, PathValue, useField} from 'react-f0rm';
|
|
1105
|
-
|
|
1106
|
-
interface Values {
|
|
1107
|
-
user: {name: string};
|
|
1108
|
-
tags: string[];
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
// 'user' | 'user.name' | 'tags' | `tags[0]` | ...
|
|
1112
|
-
type ValuesPath = FieldPath<Values>;
|
|
1113
|
-
|
|
1114
|
-
// string
|
|
1115
|
-
type UserName = PathValue<Values, 'user.name'>;
|
|
1116
|
-
|
|
1117
|
-
function UserNameField() {
|
|
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`.
|
|
1122
|
-
const {value, onChange} = useField<Values, 'user.name'>({name: 'user.name'});
|
|
1123
|
-
return <input value={value} onChange={e => onChange(e.target.value)} />;
|
|
1124
|
-
}
|
|
1125
|
-
```
|
|
1126
|
-
|
|
1127
|
-
The same generics work on `getValue`/`setValue`/`getError` and the other path-taking helpers.
|
|
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
|
-
|
|
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`:
|
|
1135
|
-
|
|
1136
|
-
```tsx
|
|
1137
|
-
import {useFormContext, useValue} from 'react-f0rm';
|
|
1138
|
-
|
|
1139
|
-
function EmailError() {
|
|
1140
|
-
const form = useFormContext<Values>();
|
|
1141
|
-
const email = useValue(form, 'email'); // string
|
|
1142
|
-
return email === '' ? <p>Email is required</p> : null;
|
|
1143
|
-
}
|
|
1144
|
-
```
|
|
1145
|
-
|
|
1146
|
-
And a `Field` tied to a typed form infers its `validate` argument from the path — `PathValueOf<Values, P>` — via the `form` prop (a plain `string` name keeps the old permissive `any`, matching `useField`):
|
|
123
|
+
## Benchmarks
|
|
1147
124
|
|
|
1148
|
-
|
|
1149
|
-
const form = useForm<Values>();
|
|
125
|
+
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).
|
|
1150
126
|
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
validate={value => (value === undefined ? 'Tell us something' : undefined)}
|
|
1162
|
-
/>
|
|
1163
|
-
</Form>
|
|
1164
|
-
```
|
|
127
|
+
| Scenario | react-f0rm | Baseline | Speedup |
|
|
128
|
+
|---|---|---|---|
|
|
129
|
+
| 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) |
|
|
130
|
+
| Change one of 100 controlled fields | 138µs/change (~7,500 ops/s) | TanStack `form.Field`: 335µs (~3,000 ops/s) | ~2.4× |
|
|
131
|
+
| Components re-rendered per change | 1 of 100 `Field`s | — | — |
|
|
132
|
+
| 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) |
|
|
133
|
+
| `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× |
|
|
134
|
+
| Change one of 1000 controlled fields | 0.652ms/change (~1,550 ops/s) | RHF `Controller`: 1.22ms (~840 ops/s) | ~1.9× |
|
|
135
|
+
| Async validation storm — burst of 3 changes × 50 debounced async validators, settled via `trigger` | 21.4ms/burst (~47 ops/s) | — | — |
|
|
136
|
+
| `await trigger(form)` — 100 mixed validators (50 sync + 50 async) settle | 5.33ms (~196 ops/s) | — | — |
|
|
1165
137
|
|
|
1166
|
-
|
|
138
|
+
Notes:
|
|
1167
139
|
|
|
1168
|
-
|
|
140
|
+
- The uncontrolled row is the apples-to-apples `register` comparison: react-f0rm's `uncontrolled: true` runs at RHF-`register` parity while keeping errors/touched/disabled/validating reactive, which raw `register` does not. The controlled comparison uses `Controller`, RHF's per-field-subscribed counterpart, and `form.Field` is TanStack's same-model counterpart.
|
|
141
|
+
- 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.
|
|
1169
142
|
|
|
1170
|
-
|
|
1171
|
-
function TextArea({value, onChange, ...props}) {
|
|
1172
|
-
return <textarea {...props} value={value} onChange={e => onChange(e.target.value)} />;
|
|
1173
|
-
}
|
|
143
|
+
Reproduce with:
|
|
1174
144
|
|
|
1175
|
-
|
|
145
|
+
```sh
|
|
146
|
+
npx vitest bench --run test/bench/render.bench.ts test/bench/getValues.bench.ts
|
|
147
|
+
npx vitest bench --run test/bench/scale.bench.ts # the three scale scenarios above
|
|
1176
148
|
```
|
|
1177
149
|
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
```jsx
|
|
1181
|
-
import {Select} from 'react-f0rm';
|
|
1182
|
-
|
|
1183
|
-
<Select name="country">
|
|
1184
|
-
<option value="cn">China</option>
|
|
1185
|
-
<option value="jp">Japan</option>
|
|
1186
|
-
</Select>
|
|
150
|
+
## Comparison
|
|
1187
151
|
|
|
1188
|
-
|
|
1189
|
-
<option value="a">Tag A</option>
|
|
1190
|
-
<option value="b">Tag B</option>
|
|
1191
|
-
</Select>
|
|
1192
|
-
```
|
|
152
|
+
react-f0rm vs React Hook Form, TanStack Form and Formik — rendering model, schema adapters, path typing, async validation, bundle size, ecosystem maturity — lives on the [Comparison page](https://wmzy.github.io/react-f0rm/comparison) of the docs site.
|
|
1193
153
|
|
|
1194
|
-
**
|
|
154
|
+
Short version: **pick react-f0rm** for controlled components with true per-field subscriptions (design systems, editor-like forms), one Standard Schema adapter, compile-time-checked paths, `register`-style bindings when you want them, and a core at RHF's size — and you are comfortable with a young library. **Pick React Hook Form** for the mature ecosystem today (its performance edge is gone at the rendering level — see the bench notes). **TanStack Form** sits in between: the deepest possible type inference, at a larger core.
|
|
1195
155
|
|
|
1196
|
-
|
|
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
|
-
```
|
|
156
|
+
## Docs Map
|
|
1204
157
|
|
|
1205
|
-
|
|
158
|
+
- Guides: [Validation](https://wmzy.github.io/react-f0rm/guides/validation) · [Field Arrays](https://wmzy.github.io/react-f0rm/guides/field-arrays) · [Submission](https://wmzy.github.io/react-f0rm/guides/submission) · [Sub-forms](https://wmzy.github.io/react-f0rm/guides/sub-forms) · [React 19 Server Actions](https://wmzy.github.io/react-f0rm/guides/react19-server-actions) · [SSR](https://wmzy.github.io/react-f0rm/guides/ssr) · [TypeScript](https://wmzy.github.io/react-f0rm/guides/typescript) · [Custom components](https://wmzy.github.io/react-f0rm/guides/custom-components) · [UI-kit integration](https://wmzy.github.io/react-f0rm/guides/ui-integration) · [Testing](https://wmzy.github.io/react-f0rm/guides/testing) · [Hooks Reference](https://wmzy.github.io/react-f0rm/guides/hooks-reference) · [Headless & React Native](https://wmzy.github.io/react-f0rm/guides/headless-react-native)
|
|
159
|
+
- Examples: [Basic](https://wmzy.github.io/react-f0rm/examples/basic) · [Dynamic fields](https://wmzy.github.io/react-f0rm/examples/dynamic) · [Real-world form](https://wmzy.github.io/react-f0rm/examples/real-world-form) (wizard + cross-field validation + server backfill)
|
|
160
|
+
- Migration: [from Formik](https://wmzy.github.io/react-f0rm/migration/from-formik) · [from React Hook Form](https://wmzy.github.io/react-f0rm/migration/from-react-hook-form) · [from TanStack Form](https://wmzy.github.io/react-f0rm/migration/from-tanstack-form) · [Breaking changes](https://wmzy.github.io/react-f0rm/migration/breaking-changes)
|
|
1206
161
|
|
|
1207
|
-
|
|
162
|
+
## Development
|
|
1208
163
|
|
|
1209
|
-
```
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
164
|
+
```bash
|
|
165
|
+
npm test # 858 tests, vmThreads pool (~3s)
|
|
166
|
+
npm run test:watch # watch mode
|
|
167
|
+
npm run coverage # coverage report (95/90/95/95 thresholds enforced)
|
|
168
|
+
npx vitest bench --run test/bench/ # benchmarks
|
|
169
|
+
npm run bench:report # bench suite -> docs-site/docs/benchmarks.md
|
|
170
|
+
npm run build # production build (UMD + ESM + CJS)
|
|
171
|
+
npm run lint # ESLint
|
|
172
|
+
npm run storybook # Storybook dev server
|
|
173
|
+
npm run docs:build # Docusaurus build (docs-site/)
|
|
1214
174
|
```
|
|
1215
175
|
|
|
1216
|
-
##
|
|
1217
|
-
|
|
1218
|
-
Coming from another library? [Migrating from TanStack Form](./docs/from-tanstack-form.md) is the repo-level concept map — core mapping table, known differences, common pitfalls. Step-by-step migration guides live in the docs site:
|
|
1219
|
-
|
|
1220
|
-
- [Migrating from Formik](docs-site/docs/migration/from-formik.md)
|
|
1221
|
-
- [Migrating from React Hook Form](docs-site/docs/migration/from-react-hook-form.md)
|
|
1222
|
-
- [Migrating from TanStack Form](docs-site/docs/migration/from-tanstack-form.md)
|
|
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
|
-
|
|
1231
|
-
## Breaking changes in 0.2
|
|
176
|
+
## License
|
|
1232
177
|
|
|
1233
|
-
|
|
178
|
+
ISC
|