# Formisch > The lightweight, schema-first and fully type-safe form library for Angular, HonoX, Preact, Qwik, React, React Native, Solid, Svelte and Vue. ## Get started (guides) ### Introduction Formisch is a schema-based, headless form library for React. It manages form state and validation. It is type-safe, fast by default and its bundle size is small due to its modular design. Try it out in our [playground](/playground/login/)! #### Highlights - Small bundle size starting at 2.5 kB - Schema-based validation with Valibot - Type safety with autocompletion in editor - Open source and fully tested with 100% coverage - It's fast – re-renders only if necessary - Minimal, readable and well thought out API - Supports all native HTML form fields #### Example Every form starts with the [`useForm`](/react/api/useForm.md) hook. It initializes your form's store based on the provided Valibot schema and infers its types. Next, wrap your form in the [`
`](/react/api/Form.md) component. It's a thin layer around the native `` element that handles form validation and submission. Then, you can access the state of a field with the [`useField`](/react/api/useField.md) hook or the [``](/react/api/Field.md) component to connect your inputs. ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema, }); return ( console.log(output)}> {(field) => (
{field.errors &&
{field.errors[0]}
}
)}
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
); } ``` In addition, Formisch offers several functions (we call them "methods") that can be used to read and manipulate the form state. These include [`focus`](/methods/api/focus.md), [`getDeepErrorEntries`](/methods/api/getDeepErrorEntries.md), [`getDeepErrors`](/methods/api/getDeepErrors.md), [`getDirtyInput`](/methods/api/getDirtyInput.md), [`getDirtyPaths`](/methods/api/getDirtyPaths.md), [`getErrors`](/methods/api/getErrors.md), [`getInput`](/methods/api/getInput.md), [`handleSubmit`](/methods/api/handleSubmit.md), [`insert`](/methods/api/insert.md), [`isDirty`](/methods/api/isDirty.md), [`isEdited`](/methods/api/isEdited.md), [`isTouched`](/methods/api/isTouched.md), [`isValid`](/methods/api/isValid.md), [`move`](/methods/api/move.md), [`pickDirty`](/methods/api/pickDirty.md), [`remove`](/methods/api/remove.md), [`replace`](/methods/api/replace.md), [`reset`](/methods/api/reset.md), [`setErrors`](/methods/api/setErrors.md), [`setInput`](/methods/api/setInput.md), [`submit`](/methods/api/submit.md), [`swap`](/methods/api/swap.md) and [`validate`](/methods/api/validate.md). These methods allow you to control the form programmatically. #### Comparison What makes Formisch unique is its framework-agnostic core, which is fully native to the framework you are using. It works by inserting framework-specific reactivity blocks when the core package is built, giving you native performance for any UI update. A modular methods API keeps bundles starting at just ~2.5 kB by only including the methods you import, and end-to-end type safety covers deeply nested paths and field arrays with TypeScript inference that stays fast even as forms grow. For a side-by-side look at how Formisch compares to React Hook Form and TanStack Form, see the [comparison guide](/react/guides/comparison.md). #### Vision My vision for Formisch is to create a framework-agnostic platform similar to [Vite](https://vite.dev/), but for forms — a shared core that lets the same mental model and codebase work natively across every modern UI framework. #### Feedback Find a bug or have an idea how to improve the library? Please fill out an [issue](https://github.com/open-circle/formisch/issues/new). Together we can make forms even better! #### License This project is available free of charge and licensed under the [MIT license](https://github.com/open-circle/formisch/blob/main/LICENSE.md). ### Installation Below you will learn how to add Formisch to your project. #### TypeScript If you are using TypeScript, we recommend that you enable strict mode in your `tsconfig.json` so that all types are calculated correctly. > The minimum required TypeScript version is v5.0.2. ```jsonc { "compilerOptions": { "strict": true, // ... }, } ``` #### Install Valibot Formisch uses [Valibot](https://valibot.dev/) for schema-based validation. You need to install it first because it is a peer dependency. ```bash npm install valibot # npm yarn add valibot # yarn pnpm add valibot # pnpm bun add valibot # bun deno add npm:valibot # deno ``` #### Install Formisch You can add Formisch to your project with a single command using your favorite package manager. ```bash npm install @formisch/react # npm yarn add @formisch/react # yarn pnpm add @formisch/react # pnpm bun add @formisch/react # bun deno add npm:@formisch/react # deno ``` Then you can import it into any JavaScript or TypeScript file. ```ts import { … } from '@formisch/react'; ``` #### For AI Agents We provide agent skills that teach AI agents the correct patterns for working with Valibot and Formisch. You can install them by running the following command in your terminal: ```bash npx skills add open-circle/agent-skills --skill formisch valibot ``` You can learn more about the Valibot and Formisch agent skill [here](https://github.com/open-circle/agent-skills). ### Coding agents Formisch is built to be consumed by AI coding agents. This page describes the agent skill, MCP server and Markdown documentation we provide so that your AI tools generate correct React code with Formisch. #### Agent skill Formisch defines form values and validation with [Valibot](https://valibot.dev/) schemas, so an agent needs two skills: our [Formisch SKILL.md](https://github.com/open-circle/agent-skills/blob/main/skills/formisch/SKILL.md) for building forms and managing form state, and the [Valibot SKILL.md](https://github.com/open-circle/agent-skills/blob/main/skills/valibot/SKILL.md) for writing the schemas. Install both with the [Agent Skills CLI](https://agentskills.io/): ```bash npx skills add open-circle/agent-skills --skill formisch valibot ``` The Formisch skill is also published at [`/.well-known/agent-skills/formisch/SKILL.md`](/.well-known/agent-skills/formisch/SKILL.md) and listed in our [discovery index](/.well-known/agent-skills/index.json). For Valibot's MCP server and llms.txt files, see [Valibot's coding agents guide](https://valibot.dev/guides/coding-agents/). #### MCP server We host a [Model Context Protocol](https://modelcontextprotocol.io/) server at `https://formisch.dev/mcp` that gives coding agents first-class tools to search and read the documentation instead of crawling pages. It is free and requires no authentication. The server provides three tools: - `search_docs` searches the documentation and returns the most relevant pages - `get_doc` reads a documentation page or blog post as Markdown - `list_docs` lists all pages grouped by framework and area Add it to Claude Code with: ```bash claude mcp add --transport http formisch https://formisch.dev/mcp ``` Or add it to the MCP configuration of your tool: ```jsonc { "mcpServers": { "formisch": { "url": "https://formisch.dev/mcp", }, }, } ``` The server metadata is available at [`/.well-known/mcp/server-card.json`](/.well-known/mcp/server-card.json). #### LLMs.txt We provide several [LLMs.txt](https://llmstxt.org/) files. Use the one that works best with your AI tool. - [`llms.txt`](/llms.txt) contains a table of contents with links to all Markdown files - [`llms-react.txt`](/llms-react.txt) contains a table of contents with links to React-related files - [`llms-react-full.txt`](/llms-react-full.txt) contains the Markdown content of the entire React docs - [`llms-react-guides.txt`](/llms-react-guides.txt) contains the Markdown content of the React guides - [`llms-react-api.txt`](/llms-react-api.txt) contains the Markdown content of the React API reference - [`llms-blog.txt`](/llms-blog.txt) contains the Markdown content of all blog posts #### Markdown for agents Every documentation page is available as Markdown. Append `.md` to the URL of a page (e.g. `/react/guides/installation/` becomes [`/react/guides/installation.md`](/react/guides/installation.md)) or request the page with an `Accept: text/markdown` header to receive its Markdown version. #### Custom building blocks Coding agents can use `@formisch/react/internals` to build custom methods and framework bindings with the same core helpers as Formisch. See the [internals guide](/react/guides/internals.md) for a typed example and guidance on reactivity and lifecycle behavior. ### Comparison Formisch is one of several form libraries available for React. The two most common alternatives are [React Hook Form](https://react-hook-form.com) and [TanStack Form](https://tanstack.com/form/latest). This page is meant as a quick reference for picking the right tool. For a deeper explanation of the architectural differences and the reasoning behind each row of the table below, see our [long-form comparison article](/blog/react-form-library-comparison.md). #### At a glance | | **Formisch** | React Hook Form | TanStack Form | | ---------------------- | --------------------------------------------------------------------- | --------------------------------------------- | --------------------------------------- | | Type source | Inferred from schema | Generic you declare | Inferred from `defaultValues` | | Validation location | Defined in schema | Per-field, resolver, or form-level `validate` | Per-validator config | | Validation timing | Form-wide `validate` / `revalidate` | Form-wide `mode` option | Per-validator trigger | | Async validation | Built-in via schema | Manual loading state | Built-in `isValidating` | | Re-render scope | Automatic per signal | Manual via `watch` / `useFormState` | Automatic per subscription | | Schema libraries | Valibot | Any via resolvers | Standard Schema | | Bundle size (min+gzip) | From ~2.5 kB | ~12 kB | ~15 kB | | Framework support | Angular, React, React Native, Preact, Solid, Svelte, Vue, Qwik, HonoX | React | React, Vue, Solid, Svelte, Lit, Angular | The table is intentionally short. It only covers the dimensions that most often drive a library choice in practice. Other differences such as devtools, ecosystem maturity, and community size are real but tend to matter less than how each library handles types, validation, and re-renders. #### Why Formisch? Three reasons to pick Formisch over the alternatives above: **One schema, no second source of truth.** A single Valibot schema is everything the form needs: the runtime validator, the source of types, and the description of the form's structure — all at once. There is no separate TypeScript generic to declare, no `defaultValues` object to keep aligned with the schema, no resolver to configure. When the schema changes, every part of the form follows — at compile time and at runtime. **The smallest bundle, by a wide margin.** Formisch starts at ~2.5 kB and grows only as you import additional methods like `focus`, `getInput`, and `reset`. That is several times smaller than the alternatives in the table above — and it stays that way because the core is intentionally small and the library is fully tree-shakeable, so methods you don't import don't end up in your bundle. **Type safety that stays fast.** Types flow from the schema through every API, including deeply nested paths and field arrays. The inference is structured to keep TypeScript editor performance from degrading as schemas grow — which matters in large codebases where heavily-generic form libraries become a friction point. #### Which library should you use? **React Hook Form** is a mature, well-documented choice with a large community and years of production usage. For simple to moderately complex forms, it remains a reasonable default. The tradeoffs only become visible as forms grow: types and schema drift out of sync, validation rules spread across components, and re-render scope becomes your responsibility. **TanStack Form** is a good fit when you need fine-grained control over validation timing and built-in async validation handling without building that infrastructure yourself. It is also the natural choice if your team is already invested in the TanStack ecosystem and values a consistent mental model across data fetching, routing, and forms. **Formisch** makes the most sense for new projects in TypeScript-heavy codebases, especially when you expect forms to grow in complexity. The schema-first design means there is a single source of truth for types, runtime validation, and form structure, so there is less to keep aligned over time. The main consideration is that Formisch currently supports only [Valibot](https://valibot.dev) as the schema library. #### Migrating to Formisch Migrating to Formisch is a genuine rewrite of the form layer, not a drop-in replacement. The mental model is different: instead of starting from a component and attaching form behavior to it, you start from a schema and build the component around it. The libraries can coexist in the same application, so you can migrate one form at a time. We provide a dedicated migration guide for each library, with a side-by-side example, step-by-step instructions, and an API mapping table: [migrate from React Hook Form](/react/guides/migrate-from-react-hook-form.md) and [migrate from TanStack Form](/react/guides/migrate-from-tanstack-form.md). A [migrate from Formik](/react/guides/migrate-from-formik.md) guide is also available. #### Next steps If you have decided that Formisch is a good fit, install it via the [installation](/react/guides/installation.md) guide and start building by [defining your form](/react/guides/define-your-form.md). ## Main concepts (guides) ### Define your form Creating a form in Formisch starts with defining a Valibot schema. The schema serves as the blueprint for your form, outlining the structure, data types, and validation rules for each field. #### Schema definition Formisch is a schema-first form library built on top of [Valibot](https://valibot.dev/). When you create a form with [`useForm`](/react/api/useForm.md), TypeScript types are automatically inferred from your schema, giving you full autocompletion and type safety throughout your form without needing to write any manual type definitions. ##### Example schema The following schema defines a form with two required string fields. The `email` field must be a valid email format, and the `password` field must be at least 8 characters long. Each validation includes custom error messages that will be displayed when validation fails. > For more complex schema examples, check out the schemas of our [playground](/playground/login/). ```ts import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); ``` ##### Field order The order in which you define fields in your schema matters. When a form is submitted with invalid values, Formisch focuses the first field with an error. Since this follows your schema, define your fields in the same order they appear in your form, so the focus moves to the first invalid field instead of one further down the page. #### Schema validation Your schema definition should reflect exactly the data you expect when submitting the form. For example, if the value of a field is optional and will only be submitted in certain cases, your schema should reflect this information by using `v.optional(…)`. ```ts import * as v from 'valibot'; const ProfileSchema = v.object({ name: v.pipe(v.string(), v.nonEmpty()), bio: v.optional(v.string()), // <- Optional field }); ``` Formisch validates your form values against the schema before submission, ensuring that your form can only be submitted if it matches your schema definition. #### Next steps Now that you understand how to define your form schema, continue to the [create your form](/react/guides/create-your-form.md) guide to learn how to initialize your form with [`useForm`](/react/api/useForm.md). ### Create your form Formisch consists of hooks, components and methods. To create a form you use the [`useForm`](/react/api/useForm.md) hook. #### Form hook The [`useForm`](/react/api/useForm.md) hook initializes and returns the store of your form. The store contains the state of the form and can be used with other Formisch hooks, components and methods to build your form. ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema, }); return (
console.log(output)}> {/* Form fields will go here */}
); } ``` ##### Configuration options The [`useForm`](/react/api/useForm.md) hook accepts a configuration object with the following options: - `schema`: Your Valibot schema that defines the form - `initialInput`: Initial values for your form fields (optional) - `emptyInput`: The empty value each field type starts at when a required field has no initial input (optional, defaults to `{ string: '' }`) - `validate`: When validation first occurs (optional, defaults to `'submit'`) - `revalidate`: When revalidation occurs after initial validation (optional, defaults to `'input'`) ```tsx const loginForm = useForm({ schema: LoginSchema, initialInput: { email: 'user@example.com', }, validate: 'initial', revalidate: 'input', }); ``` Formisch tracks two inputs for every field: the **initial input** (baseline for dirty tracking) and the **current input** (what the user is editing). In many apps, the initial input represents the server state while the current input represents the client state. `isDirty` becomes `true` when a field's current input differs from its initial input. Use [`setInput`](/methods/api/setInput.md) to update the current input (client state), and use [`reset`](/methods/api/reset.md) to update the initial input (baseline) when your server data changes or is refreshed. ##### Empty input By default, a required string field starts as an empty string (`''`) instead of `undefined`, matching an empty text input. This way an empty field shows the validation message you defined for it (for example from `v.nonEmpty()`) without you setting an `initialInput` for every field. You can configure the empty value per field type, or opt out by setting a type to `undefined`: ```tsx const loginForm = useForm({ schema: LoginSchema, emptyInput: { string: '', // the default number: 0, // required numbers start at 0 instead of undefined boolean: false, // checkboxes start unchecked }, }); ``` Optional and nullable fields are never affected and keep starting as `undefined`, since they accept it. The supported types are `string`, `number`, `boolean` and `date`, and the default is `{ string: '' }`. #### Multiple forms When a page contains multiple forms, you can create separate form stores for each one: ```tsx import { Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); const RegisterSchema = v.object({ username: v.pipe(v.string(), v.minLength(3)), email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema }); const registerForm = useForm({ schema: RegisterSchema }); return ( <>
console.log(output)}> {/* … */}
console.log(output)}> {/* … */}
); } ``` If you need a multi-step form (wizard), see the [multi-step form discussion](https://github.com/open-circle/formisch/discussions/108) for patterns and approaches. #### Next steps Now that you know how to create a form, continue to the [add form fields](/react/guides/add-form-fields.md) guide to learn how to connect your input elements to the form using the [`Field`](/react/api/Field.md) component. ### Add form fields To add a field to your form, you can use the [`Field`](/react/api/Field.md) component or the [`useField`](/react/api/useField.md) hook. Both are headless and provide access to field state for building your form UI. #### Field component The [`Field`](/react/api/Field.md) component has two mandatory properties: `of` which accepts the form store, and `path` which specifies which field to connect. If you use TypeScript, you get full autocompletion for the path based on your schema. ##### Children prop As a child, you pass a function to the [`Field`](/react/api/Field.md) component that returns JSX. The function receives the field store as its parameter, which includes the current value, error messages, and props to spread onto your input element. ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema, }); return (
console.log(output)}> {(field) => } {(field) => ( )}
); } ``` > **Important:** The event handlers in `field.props` read the value from the DOM as a string. Fields with a non-string schema like `v.number()` or `v.date()` therefore need to be controlled to store the value with the correct type. See the [controlled fields](/react/guides/controlled-fields.md) guide to learn more. > **Important:** If you plan to set initial values with `initialInput` or programmatically control field values using methods like [`setInput`](/methods/api/setInput.md) or [`reset`](/methods/api/reset.md), you must make your fields controlled by setting the appropriate attributes (like `value`, `checked`, or `selected`). See the [controlled fields](/react/guides/controlled-fields.md) guide to learn more. ##### Headless design The [`Field`](/react/api/Field.md) component does not render its own UI elements. It is headless and provides only the data layer of the field. This allows you to freely define your user interface. You can use HTML elements, custom components or an external UI library. ##### Path array The `path` property accepts an array of strings and numbers that represents the path to the field in your schema. For top-level fields, it's simply the field name wrapped in an array: ```tsx {(field) => } ``` For nested fields, the path reflects the structure of your schema: ```tsx // For a schema like: v.object({ user: v.object({ email: v.string() }) }) {(field) => } ``` ##### Type safety The API design of the [`Field`](/react/api/Field.md) component results in a fully type-safe form. For example, if you change your schema, TypeScript will immediately alert you if the path is invalid. The field state is also fully typed based on your schema, giving you autocompletion for properties like `field.input`. #### useField hook For very complex forms where you create individual components for each form field, Formisch provides the [`useField`](/react/api/useField.md) hook. It allows you to access the field state directly within your component logic. ```tsx import { useField } from '@formisch/react'; import type { FormStore } from '@formisch/react'; import * as v from 'valibot'; type EmailInputProps = { form: FormStore>; }; function EmailInput(props: EmailInputProps) { const field = useField(props.form, { path: ['email'] }); return (
{field.errors &&
{field.errors[0]}
}
); } ``` ##### When to use which - **Use [`Field`](/react/api/Field.md) component**: When defining multiple fields in the same component. It ensures you don't accidentally access the wrong field store. - **Use [`useField`](/react/api/useField.md) hook**: When creating field components for single fields. It allows you to access field state in your component logic. The [`Field`](/react/api/Field.md) component is essentially a thin wrapper around [`useField`](/react/api/useField.md) that allows you to access the field state within JSX code. #### Field store The field store provides access to the following properties. They are plain values, but because Formisch wires into React's rendering, your components re-render when they change. - `path`: The path to the field within the form. - `props`: JSX props to spread onto your input element (includes event handlers, ref callback, name attribute, and `autoFocus` to automatically focus fields with errors). - `input`: The current input value of the field. - `errors`: The current array of error messages if validation fails. - `isTouched`: Whether the field has been touched. - `isEdited`: Whether the field's value has been changed. - `isDirty`: Whether the current input differs from the initial input. - `isValid`: Whether the field passes all validation rules. - `onChange`: Sets the field input value programmatically. Use this when the field cannot be connected to a native HTML element (e.g., complex custom inputs or component libraries that don't expose the underlying element). #### Next steps Now that you know how to add fields to your form, continue to the [input components](/react/guides/input-components.md) guide to learn about creating reusable input components for your forms. ### Input components To make your code more readable, we recommend that you develop your own input components if you are not using a prebuilt UI library. There you can encapsulate logic to display error messages, for example. > If you're already a bit more experienced, you can use the input components we developed for our [playground](/playground/login/) as a starting point. You can find the code in our GitHub repository [here](https://github.com/open-circle/formisch/tree/main/playgrounds/react/src/components). #### Why input components? Currently, your fields might look something like this: ```tsx {(field) => (
{field.errors &&
{field.errors[0]}
}
)}
``` If CSS and a few more functionalities are added here, the code quickly becomes confusing. In addition, you have to rewrite the same code for almost every form field. Our goal is to develop a `TextInput` component so that the code ends up looking like this: ```tsx {(field) => ( )} ``` #### Create an input component In the first step, you create a new file for the `TextInput` component and, if you use TypeScript, define its properties. ```tsx import type { FieldElementProps } from '@formisch/react'; interface TextInputProps extends FieldElementProps { type: 'text' | 'email' | 'tel' | 'password' | 'url' | 'date'; label?: string; placeholder?: string; input: string | undefined; errors: [string, ...string[]] | null; required?: boolean; } ``` ##### Component function In the next step, add the component function to the file. We can destructure props directly and spread the remaining props. ```tsx import type { FieldElementProps } from '@formisch/react'; interface TextInputProps extends FieldElementProps { /* ... */ } export function TextInput({ label, input, errors, ...props }: TextInputProps) { // Component implementation } ``` ##### JSX code After that, you can add the JSX code to the return statement. ```tsx import type { FieldElementProps } from '@formisch/react'; interface TextInputProps extends FieldElementProps { /* ... */ } export function TextInput({ label, input, errors, ...props }: TextInputProps) { const { name, required } = props; return (
{label && ( )} {errors &&
{errors[0]}
}
); } ``` ##### Next steps You can now build on this code and add CSS, for example. You can also follow the procedure to create other components such as `Checkbox`, `Slider`, `Select` and `FileInput`. ##### Final code Below is an overview of the entire code of the `TextInput` component. ```tsx import type { FieldElementProps } from '@formisch/react'; interface TextInputProps extends FieldElementProps { type: 'text' | 'email' | 'tel' | 'password' | 'url' | 'date'; label?: string; placeholder?: string; input: string | undefined; errors: [string, ...string[]] | null; required?: boolean; } export function TextInput({ label, input, errors, ...props }: TextInputProps) { const { name, required } = props; return (
{label && ( )} {errors &&
{errors[0]}
}
); } ``` #### Using component libraries When using component libraries that don't expose their underlying native HTML elements, you cannot spread `field.props` directly. Instead, use `field.onChange` to update the value programmatically: ```tsx import { DatePicker } from 'some-component-library'; {(field) => ( field.onChange(newDate)} /> )} ; ``` The `field.onChange` method updates the field value and triggers validation. For more details, see the [controlled fields](/react/guides/controlled-fields.md) guide. For ready-made wiring recipes, check out our integration guides: - [shadcn/ui](/react/guides/shadcn-ui.md) - [Ark UI](/react/guides/ark-ui.md) - [Base UI](/react/guides/base-ui.md) - [Chakra UI](/react/guides/chakra-ui.md) - [Mantine](/react/guides/mantine.md) - [React Aria](/react/guides/react-aria.md) #### Next steps Now that you know how to create reusable input components, continue to the [handle submission](/react/guides/handle-submission.md) guide to learn how to process form data when the user submits the form. ### Handle submission Your first form is almost ready. The remaining step is processing its data when the form is submitted. #### Submit event To process the values on submission, you need to pass a function to the `onSubmit` property of the [`Form`](/react/api/Form.md) component. The first parameter passed to the function contains the validated form values. ```tsx import { Field, Form, useForm } from '@formisch/react'; import type { SubmitHandler } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema, }); const submitForm: SubmitHandler = (values) => { // Process the validated form values console.log(values); // { email: string, password: string } }; return (
{/* Form fields will go here */}
); } ``` The [`SubmitHandler`](/core/api/SubmitHandler.md) type ensures type safety for your submission handler, automatically inferring the types of validated values from your schema. If you need access to the submit event, use [`SubmitEventHandler`](/core/api/SubmitEventHandler.md) instead. ##### Prevent default When the form is submitted, `event.preventDefault()` is executed by default to prevent the window from reloading so that the values can be processed directly in the browser and the state of the form is preserved. ##### Loading state While the form is being submitted, you can use `loginForm.isSubmitting` to display a loading animation and disable the submit button: ```tsx ``` The form store also provides other reactive properties like `isSubmitted`, `isValidating`, `isTouched`, `isDirty`, `isValid`, and `errors` for tracking form state. Note that `errors` only contains validation errors at the root level of the form — to get all errors from all fields, use the [`getDeepErrors`](/methods/api/getDeepErrors.md) method. ##### Async submission The submit handler can be asynchronous, allowing you to perform API calls or other async operations: ```tsx const submitForm: SubmitHandler = async (values) => { try { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values), }); if (response.ok) { // Handle successful login console.log('Login successful!'); } else { // Handle error console.error('Login failed'); } } catch (error) { console.error('Error during submission:', error); } }; ``` ##### Trigger submission If you want to trigger submission programmatically from outside the form, you can use the [`submit`](/methods/api/submit.md) method. It calls `requestSubmit()` on the underlying form element: ```tsx import { submit } from '@formisch/react'; ; ``` #### Submit without \
In some cases, you may not be able to wrap your fields in a `` element — for example, when your form is rendered inside another form, since nesting `` elements is invalid HTML. In these situations, you can use the [`handleSubmit`](/methods/api/handleSubmit.md) method directly to submit the form programmatically without the [`Form`](/react/api/Form.md) component. The returned function accepts no arguments and can be called from anywhere — for example, from a button's `onClick` handler: ```tsx import { Field, handleSubmit, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema, }); const submitForm = handleSubmit(loginForm, (values) => { // Process the validated form values console.log(values); }); return (
{/* Form fields without a wrapper */}
); } ``` #### Next steps Congratulations! You've learned the core concepts of building forms with Formisch. To learn more about advanced features, check out the [form methods](/react/guides/form-methods.md) guide to discover how to programmatically control your forms. ### Form methods To retrieve the values of your form or to make changes to the form, Formisch provides you with several methods. These apply either to the entire form or to individual fields. #### Reading values To retrieve values from your form, you can use: - [`getInput`](/methods/api/getInput.md): Get the current value of a specific field - [`getErrors`](/methods/api/getErrors.md): Get error messages for a specific field - [`getDeepError`](/methods/api/getDeepError.md): Get the first error message within a field or the form - [`getDeepErrors`](/methods/api/getDeepErrors.md): Get all error messages across the entire form - [`getDeepErrorEntry`](/methods/api/getDeepErrorEntry.md): Get the error messages of the first erroring field paired with its path - [`getDeepErrorEntries`](/methods/api/getDeepErrorEntries.md): Get all error messages paired with the path of the field they belong to Formisch plugs into React's render cycle, so reading values with these methods inside components stays reactive. When the form state changes, components that rely on these values automatically re-render without manual subscriptions. #### Field state To check the state of a single field or of the entire form, use: - [`isTouched`](/methods/api/isTouched.md): Whether the field or form has been touched - [`isEdited`](/methods/api/isEdited.md): Whether the field or form has been edited - [`isDirty`](/methods/api/isDirty.md): Whether the field or form differs from its initial input - [`isValid`](/methods/api/isValid.md): Whether the field or form has no validation errors Each of these takes an optional `path` to scope the check to a single field. Without it, they walk the entire form. #### Dirty state To work with the dirty state of your form, Formisch provides three methods: - [`getDirtyInput`](/methods/api/getDirtyInput.md): Get the dirty parts of the form input - [`getDirtyPaths`](/methods/api/getDirtyPaths.md): Get the paths of dirty fields - [`pickDirty`](/methods/api/pickDirty.md): Filter an externally-supplied value down to its dirty parts using the form's dirty mask See the [dirty fields](/react/guides/dirty-fields.md) guide for when to reach for each. #### Setting values To manually update form values or errors, use: - [`setInput`](/methods/api/setInput.md): Manually update the value of a specific field - [`setErrors`](/methods/api/setErrors.md): Manually set error messages for a specific field > When you have access to a field store (from [`useField`](/react/api/useField.md) or [`Field`](/react/api/Field.md)), you can use `field.onChange(value)` to update the value directly. This is especially useful for custom inputs or component libraries that don't expose native HTML elements. > If you need to update the form because the initial data has changed (e.g., remote data was refreshed), use [`reset`](/methods/api/reset.md) with a new `initialInput` instead of [`setInput`](/methods/api/setInput.md). The [`reset`](/methods/api/reset.md) method properly reinitializes the form state, while [`setInput`](/methods/api/setInput.md) only changes the current input values without updating the initial state. #### Form control To control the form programmatically, use: - [`handleSubmit`](/methods/api/handleSubmit.md): Create a submit event handler that validates the form and calls your handler on success - [`reset`](/methods/api/reset.md): Reset the form to its initial state or update initial values - [`validate`](/methods/api/validate.md): Manually trigger validation of the entire form - [`submit`](/methods/api/submit.md): Programmatically trigger form submission - [`focus`](/methods/api/focus.md): Focus on a specific field #### Array operations For working with field arrays, Formisch provides: - [`insert`](/methods/api/insert.md): Insert a new item into a field array - [`remove`](/methods/api/remove.md): Remove an item from a field array - [`move`](/methods/api/move.md): Move an item to a different position in a field array - [`swap`](/methods/api/swap.md): Swap two items in a field array - [`replace`](/methods/api/replace.md): Replace an item in a field array #### API design All methods in Formisch follow a consistent API pattern: the first parameter is always the form store, and the second parameter (if necessary) is always a config object. This design makes the API flexible and consistent across all methods. Once you understand this pattern, you basically understand the entire API design. Here are some examples: ```tsx // Get the value of a field const emailInput = getInput(loginForm, { path: ['email'] }); // Reset the form with new initial values reset(loginForm, { initialInput: { email: '', password: '' } }); // Move an item in a field array move(loginForm, { path: ['items'], from: 0, to: 3 }); ``` #### API reference You can find detailed documentation for each method in our [API reference](/react/api/). ## Advanced guides (guides) ### Validation Formisch validates your form against your Valibot schema — the same one that defines its types. This guide explains how validation runs under the hood, how the `validate` and `revalidate` config control its timing, how to display errors only when they are helpful, and how to react to asynchronous validation with `isValidating`. #### How validation works Whenever validation is triggered, Formisch parses the **entire form** against your schema in a single pass. It then distributes the resulting issues to the individual fields: every field with an issue receives its error messages, and every field without one is cleared. A field is valid when it has no errors. > Validation always runs against the whole schema, even when a single field triggers it. This keeps cross-field rules (like a `password` and `confirmPassword` that must match) correct without any extra wiring. The result is still stored per field, so each `` only re-renders when its own errors change. Because Formisch parses with Valibot's asynchronous API, schemas with async checks (for example, a server-side uniqueness check) work out of the box. While such a check is in flight, the form's `isValidating` state is `true` (see [below](#validating-state)). #### When validation runs Two config options control the timing of validation: - `validate`: when a field is validated for the **first** time. Defaults to `'submit'`. - `revalidate`: when a field is validated **again**, once it already has an error or the form has been submitted. Defaults to `'input'`. Both accept the following modes: - `'initial'`: immediately, when the form is created (only valid for `validate`, not `revalidate`). - `'touch'`: when the field is first focused. - `'input'`: on every keystroke. - `'change'`: on the field's change event. - `'blur'`: when the field loses focus. - `'submit'`: only when the form is submitted. ```tsx const loginForm = useForm({ schema: LoginSchema, validate: 'blur', revalidate: 'input', }); ``` The split between `validate` and `revalidate` is what makes good defaults possible. With the default `validate: 'submit'` and `revalidate: 'input'`, a field stays quiet until the user submits, and only then does it start correcting itself live as the user fixes it. The configuration above (`validate: 'blur'`) is a gentler variant: a field is first checked when the user leaves it, then re-checked on every keystroke once it has an error. #### Showing errors at the right time `validate` and `revalidate` control **when validation runs** — but not **when errors are shown**. After a validation pass, every invalid field has its `errors` populated, and it is up to you to decide which ones to render. Showing every error the moment it appears can overwhelm the user, while showing them only after submit forces them to scroll back and fix fields they have already filled out. A balanced approach is to reveal a field's error once the user has actually changed it, and to reveal all remaining errors after the first submit attempt. Each field exposes several state flags to drive this decision: - `isTouched`: the field has been focused or changed. - `isEdited`: the field's value has been changed (but not merely focused), and stays `true` even if the value is changed back to its initial value. - `isDirty`: the field's current value differs from its initial value. The form additionally exposes `isSubmitted`, which becomes `true` after the first submit attempt. Combining `isEdited` with `isSubmitted` gives the balanced behavior described above: ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function App() { const loginForm = useForm({ schema: LoginSchema, validate: 'change', }); return ( console.log(output)}> {(field) => (
{(field.isEdited || loginForm.isSubmitted) && field.errors && (
{field.errors[0]}
)}
)}
); } ``` `isEdited` is the right flag for this. `isTouched` would reveal the error as soon as the user tabs through a field without changing it, and `isDirty` would hide the error again if the user clears an invalid value back to its initial state. `isEdited` avoids both: it turns on only after a real change and stays on. Pair it with `validate: 'input'` (or `'change'`) so the error appears as soon as the field becomes invalid, and with `isSubmitted` so that the errors of all fields — including the ones the user never touched — become visible after a submit attempt. ##### Reuse the guard across fields Writing this guard at every field gets repetitive. The common fix is to move it into a small reusable component, either on its own or folded into the `TextInput` from the [input components](/react/guides/input-components.md) guide, so the `isEdited || isSubmitted` logic lives in exactly one place: ```tsx interface FieldErrorProps { errors: [string, ...string[]] | null; isEdited: boolean; isSubmitted: boolean; } export function FieldError({ errors, isEdited, isSubmitted }: FieldErrorProps) { if (!errors || (!isEdited && !isSubmitted)) { return null; } return
{errors[0]}
; } ``` Each field then stays focused on its input: ```tsx {(field) => (
)}
``` #### Validating state When your schema contains asynchronous checks, validation does not resolve instantly. The form's `isValidating` state is `true` while any validation is in flight, which you can use to show a loading indicator or to disable the submit button until validation settles. ```tsx import { Form, useForm } from '@formisch/react'; import * as v from 'valibot'; import { isUsernameAvailable } from '~/api'; const SignUpSchema = v.objectAsync({ username: v.pipeAsync( v.string(), v.nonEmpty(), v.checkAsync(isUsernameAvailable, 'Username is already taken.') ), }); export default function App() { const signUpForm = useForm({ schema: SignUpSchema, validate: 'blur', }); return (
console.log(output)}> {/* fields */}
); } ``` `isValidating` and `isSubmitting` overlap but are not the same. `isValidating` is `true` whenever validation runs — triggered by a field event or as part of a submit. `isSubmitting` is `true` for the entire submission, which covers both validating the form and running your submit handler. So during a submit both are `true` while the form validates, and once validation passes only `isSubmitting` stays `true` while your handler runs. #### Further reading To process your form's values once they pass validation, see the [handle submission](/react/guides/handle-submission.md) guide. For working with the fields a user has changed, see the [dirty fields](/react/guides/dirty-fields.md) guide. ### Special inputs As listed in our features, the library supports all native HTML form fields. This includes the HTML `` element. > In our [playground](/playground/special/) you can take a look at such fields and test them out. #### Checkbox A simple checkbox represents a boolean and is `true` when checked or `false` otherwise. ```tsx {(field) => ( )} ``` However, you can also use multiple checkboxes to represent an array of strings. For this you simply have to add the `value` attribute to the HTML `` element. ```tsx <> {[ { label: 'Bananas', value: 'bananas' }, { label: 'Apples', value: 'apples' }, { label: 'Grapes', value: 'grapes' }, ].map(({ label, value }) => ( {(field) => ( )} ))} ``` #### Radio A group of radio buttons, while similar to an array of checkboxes, will only allow you to select one of the options based on which button is checked. ```tsx {(field) => ( <> {[ { label: 'Red', value: 'red' }, { label: 'Green', value: 'green' }, { label: 'Blue', value: 'blue' }, ].map(({ label, value }) => ( ))} )} ``` #### Select An HTML ` {[ { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Qwik', value: 'qwik' }, ].map(({ label, value }) => ( ))} )}
``` However, if you set the `multiple` attribute, multiple options can be selected making the field represent an array of strings. ```tsx {(field) => ( // Set "multiple" to "true" )} ``` #### File An HTML `` works similarly to an HTML `} ``` With the `multiple` attribute, users can select multiple files: ```tsx {(field) => } ``` ### Controlled fields By default, all form fields are uncontrolled because that's the default behavior of the browser. For a simple login or contact form this is quite sufficient. #### Why controlled? As soon as your forms become more complex, for example you set initial values or change the values of a form field via [`setInput`](/methods/api/setInput.md), it becomes necessary that you control your fields yourself. For example, depending on which HTML form field you use, you may need to set the `value`, `checked` or `selected` attributes. ##### Text input example For a text input field you simply add the `value` attribute and pass the field's input value: ```tsx {(field) => } ``` ##### Exception for files The HTML `` element is an exception because it cannot be controlled. However, you have the possibility to control the UI around it. For inspiration you can use the code of our [`FileInput`](https://github.com/open-circle/formisch/blob/main/playgrounds/react/src/components/FileInput.tsx) component from our [playground](/playground/special/). #### Numbers and dates Fields defined with a `v.number()` or `v.date()` schema need extra steps to be controlled, because the `` element natively understands only strings as value. ##### Number input example An `` only reads and writes strings. So if you spread `field.props` onto it, `field.input` holds a string like `"123"`, even though it is typed as `number`. To store a real number, override the change handler with one that converts the value via `valueAsNumber` and forwards it to `field.onChange`. You also have to handle `NaN`. While typing a floating point number, the value can briefly be `NaN`, for example right after typing `1.`. If you don't catch this for the displayed value, the input is cleared. It is best to encapsulate both in a separate component as described in the [input components](/react/guides/input-components.md) guide. ```tsx import type { FieldElementProps } from '@formisch/react'; import { useMemo, useRef } from 'react'; interface NumberInputProps extends Omit { label?: string; placeholder?: string; input: number | undefined; errors: [string, ...string[]] | null; required?: boolean; onChange: (value: number | undefined) => void; } export function NumberInput({ label, input, errors, name, onChange, ...inputProps }: NumberInputProps) { const prevValue = useRef(); // Get value, keeping previous value if NaN const value = useMemo(() => { if (typeof input === 'number' && !Number.isNaN(input)) { prevValue.current = input; return input; } return prevValue.current; }, [input]); return (
{label && } onChange( event.currentTarget.value === '' ? undefined : event.currentTarget.valueAsNumber ) } aria-invalid={!!errors} aria-errormessage={`${name}-error`} /> {errors &&
{errors[0]}
}
); } ``` Pass `field.onChange` after spreading `field.props` so it overrides the native handler. ```tsx {(field) => ( )} ``` ##### Date input example The same applies to dates. An `` works with `yyyy-mm-dd` strings, while you usually want to store a `Date`. So you convert in both directions: format the `Date` for display, and parse the entered string back with `valueAsDate` before storing it. ```tsx import type { FieldElementProps } from '@formisch/react'; import { useMemo } from 'react'; interface DateInputProps extends Omit { label?: string; placeholder?: string; input: Date | undefined; errors: [string, ...string[]] | null; required?: boolean; onChange: (value: Date | undefined) => void; } export function DateInput({ label, input, errors, name, onChange, ...inputProps }: DateInputProps) { // Transform date to string const value = useMemo( () => input && !Number.isNaN(input.getTime()) ? input.toISOString().split('T', 1)[0] : '', [input] ); return (
{label && } onChange(event.currentTarget.valueAsDate ?? undefined) } aria-invalid={!!errors} aria-errormessage={`${name}-error`} /> {errors &&
{errors[0]}
}
); } ``` As with the number input, pass `field.onChange` after the spread to override the native handler. ```tsx {(field) => ( )} ``` #### Custom inputs and component libraries Some component libraries don't expose the underlying native HTML element, which means you cannot spread `field.props` onto them. For these cases, use `field.onChange` to set the value programmatically. ```tsx import { DatePicker } from 'some-component-library'; {(field) => ( field.onChange(newDate)} /> )} ; ``` This is useful for: - **Component libraries** that wrap native elements without exposing them - **Complex custom inputs** like date pickers, rich text editors, or color pickers The `field.onChange` method updates the field value and triggers validation, just like a native input would. For ready-made wiring recipes, check out our integration guides: - [shadcn/ui](/react/guides/shadcn-ui.md) - [Ark UI](/react/guides/ark-ui.md) - [Base UI](/react/guides/base-ui.md) - [Chakra UI](/react/guides/chakra-ui.md) - [Mantine](/react/guides/mantine.md) - [React Aria](/react/guides/react-aria.md) #### Next steps Now that you understand controlled fields, you can explore more advanced topics like [nested fields](/react/guides/nested-fields.md) and [field arrays](/react/guides/field-arrays.md) to handle complex form structures. ### Nested fields To add a little more structure to a complex form or to match the values of the form to your database, you can also nest your form fields in objects as deep as you like. #### Schema definition For example, in the schema below, the first and last name are grouped under the object with the key `name`. ```tsx import * as v from 'valibot'; const ContactSchema = v.object({ name: v.object({ first: v.pipe(v.string(), v.nonEmpty()), last: v.pipe(v.string(), v.nonEmpty()), }), email: v.pipe(v.string(), v.email()), message: v.pipe(v.string(), v.nonEmpty()), }); ``` #### Path array When creating a nested field, use an array with multiple elements for the `path` property to refer to the nested field. The array represents the path through the nested structure. ```tsx {(field) => } ``` If you're using TypeScript, your editor will provide autocompletion for the path based on your schema structure. #### Deep nesting You can nest objects as deeply as needed. Simply extend the path array with additional keys: ```tsx const ProfileSchema = v.object({ user: v.object({ address: v.object({ street: v.string(), city: v.string(), country: v.string(), }), }), }); // Access deeply nested field {(field) => } ; ``` #### Type safety The path array is fully type-safe. TypeScript will validate that each element in your path corresponds to a valid key in your schema structure, providing autocompletion and compile-time errors if you reference a non-existent path. ### Dirty fields When a user edits a form, Formisch tracks which fields have changed since they were initialized. The library exposes three methods for working with that dirty state: [`getDirtyInput`](/methods/api/getDirtyInput.md), [`getDirtyPaths`](/methods/api/getDirtyPaths.md), and [`pickDirty`](/methods/api/pickDirty.md). This guide explains what each one is for, when to reach for it, and why `pickDirty` exists alongside the others. #### What "dirty" means A field is dirty when its current input differs from its start input. The form starts clean. As the user types, only the fields they touch flip to dirty. Resetting a field (or resetting the form with a new `initialInput`) clears the dirty flag. > The dirty flag is per-field. Editing a deeply nested value does not flip its ancestors' flags. The dirty-extraction methods walk the tree internally to find dirty descendants, which is why all three methods do the same kind of work under the hood. #### The three methods ##### `getDirtyInput` Returns the dirty subtree of the form's input. Use it when you want to ship the values the user typed — typically for a PATCH endpoint that accepts the same shape as your form input. ```tsx import { Form, getDirtyInput, type SubmitHandler, useForm, } from '@formisch/react'; import * as v from 'valibot'; const UserSchema = v.object({ name: v.pipe(v.string(), v.nonEmpty()), email: v.pipe(v.string(), v.email()), }); interface EditProfileProps { user: v.InferInput & { id: string }; } export default function EditProfile({ user }: EditProfileProps) { const profileForm = useForm({ schema: UserSchema, initialInput: user, }); const onSubmit: SubmitHandler = async () => { const dirty = getDirtyInput(profileForm); if (dirty) { await api.patchUser(user.id, dirty); } }; return (
{/* fields */}
); } ``` If only `email` was edited, `dirty` is `{ email: 'new@example.com' }`. If nothing was edited, it is `undefined`. Because dirty state is bound to the form input, `getDirtyInput` always returns the raw user input. Schema transformations such as `v.trim()` or `v.toNumber()` are not applied to the returned values. When you need the validated and transformed output instead, reach for `pickDirty` (see [below](#why-pickdirty-exists)). ##### `getDirtyPaths` Returns a list of paths to dirty fields. Use it for logging, telemetry, or driving a custom walker over the form's dirty state. ```tsx import { getDirtyPaths } from '@formisch/react'; const dirtyPaths = getDirtyPaths(profileForm); // e.g. [['email'], ['user', 'name']] ``` Arrays are atomic: only the array's own path is returned, never the paths of individual items. ##### `pickDirty` Filters a user-supplied value down to its dirty parts using the form's dirty mask. Use it when you have a separately-derived value — most commonly the validated and transformed output from a submit handler — and you want only its dirty parts. ```tsx import { pickDirty, type SubmitHandler } from '@formisch/react'; const onSubmit: SubmitHandler = async (output) => { const dirty = pickDirty(profileForm, { from: output }); if (dirty) { await api.update(dirty); } }; ``` #### Why `pickDirty` exists Dirty state is tracked against the form **input** — the raw values the user typed. But Valibot schemas can transform that input into a different output shape before it reaches your submit handler: ```tsx import * as v from 'valibot'; const Schema = v.object({ name: v.pipe(v.string(), v.trim()), age: v.pipe(v.string(), v.toNumber()), }); ``` After validation, `output.name` has whitespace trimmed and `output.age` is a number. [`getDirtyInput`](/methods/api/getDirtyInput.md) would give you the raw strings, because the dirty state is bound to the form input — not to the validated output. [`pickDirty(form, { from: output })`](/methods/api/pickDirty.md) is the bridge: it walks the form's dirty tree as a structural mask and reads the corresponding values from the output you supply. The result preserves the transformed types. ```tsx import { pickDirty, type SubmitHandler } from '@formisch/react'; const onSubmit: SubmitHandler = async (output) => { // output.age is a number — pickDirty preserves that. const dirty = pickDirty(form, { from: output }); if (dirty) { await api.update(dirty); } }; ``` If the schema reshapes the output entirely — for example, by combining several input fields into a single output value — `pickDirty` returns `undefined` because the shape no longer aligns with the form's input shape. #### Atomic arrays All three methods treat arrays as atomic. When any descendant of an array is dirty, the full array is returned (or its own path, for `getDirtyPaths`). The methods never produce sparse arrays. Sparse arrays don't round-trip safely. Serializers compact them, `JSON.stringify` writes `null` for holes, and indices lose positional meaning. Returning the full current array preserves order and lets the server treat the array as a complete replacement. This differs from objects, where clean keys are omitted. Objects model keyed dictionaries; arrays model ordered sequences. #### Common patterns The snippets below assume `form` is your form store (the result of [`useForm`](/react/api/useForm.md)). ##### Skip submission when nothing changed The form's `isDirty` flag is the cheapest way to ask "is anything dirty?" — it short-circuits on the first dirty field it finds and doesn't allocate. Use it when all you need is the yes/no answer. If you actually consume the output of `getDirtyInput`, `getDirtyPaths`, or `pickDirty`, call that method directly — its return value already signals "nothing dirty", so checking `form.isDirty` first would just walk the tree twice. ```tsx import type { SubmitHandler } from '@formisch/react'; const onSubmit: SubmitHandler = async (output) => { if (!form.isDirty) { return; } await api.update(output); }; ``` ##### Send only the dirty raw input ```tsx import { getDirtyInput } from '@formisch/react'; const dirty = getDirtyInput(form); if (dirty) { await api.patch(dirty); } ``` ##### Send only the dirty validated output ```tsx import { pickDirty, type SubmitHandler } from '@formisch/react'; const onSubmit: SubmitHandler = async (output) => { const dirty = pickDirty(form, { from: output }); if (dirty) { await api.update(dirty); } }; ``` #### Performance All three methods walk the form's field tree and call `getFieldBool` recursively to skip clean subtrees. Cost is effectively linear in field count for typical balanced forms (shallow and wide) and degrades toward `O(N²)` for deeply nested trees with few siblings at each level. Call these methods from submit or blur handlers — not from tight reactive loops on every keystroke. For very large or deeply nested forms (thousands of fields), profile before binding them to high-frequency events. ### Field arrays Dynamically generating form fields from an array introduces additional challenges when items are added, removed, swapped, or moved. Formisch provides the [`FieldArray`](/react/api/FieldArray.md) component, which works with its array methods to make these forms straightforward. > In our [playground](/playground/todos/) you can take a look at a form with a field array and test it out. #### Create a field array ##### Schema definition In the following example we create a field array for a todo form with the following schema: ```tsx import * as v from 'valibot'; const TodoFormSchema = v.object({ heading: v.pipe(v.string(), v.nonEmpty()), todos: v.pipe( v.array( v.object({ label: v.pipe(v.string(), v.nonEmpty()), deadline: v.pipe(v.string(), v.nonEmpty()), }) ), v.nonEmpty(), v.maxLength(10) ), }); ``` ##### FieldArray component To dynamically generate the form fields for the todos, you use the [`FieldArray`](/react/api/FieldArray.md) component in combination with JavaScript's `Array.prototype.map()` method. The field array provides an `items` array of unique string identifiers which are used to detect when an item is added, moved, or removed. ```tsx import { Field, FieldArray, Form, useForm } from '@formisch/react'; export default function TodoPage() { const todoForm = useForm({ schema: TodoFormSchema, initialInput: { heading: '', todos: [{ label: '', deadline: '' }], }, }); return (
console.log(output)}> {(field) => ( <> {field.errors &&
{field.errors[0]}
} )}
{(fieldArray) => (
{fieldArray.items.map((item, index) => (
{(field) => ( <> {field.errors &&
{field.errors[0]}
} )}
{(field) => ( <> {field.errors &&
{field.errors[0]}
} )}
))} {fieldArray.errors &&
{fieldArray.errors[0]}
}
)}
); } ``` ##### Path array with index As with [nested fields](/react/guides/nested-fields.md), you use an array for the `path` property. The key difference is that you include the index from the `map()` function to specify which array item you're referencing. This ensures the paths update correctly when items are added, moved, or removed. ```tsx {(field) => } ``` #### Use array methods Now you can use the [`insert`](/methods/api/insert.md), [`move`](/methods/api/move.md), [`remove`](/methods/api/remove.md), [`replace`](/methods/api/replace.md), and [`swap`](/methods/api/swap.md) methods to make changes to the field array. These methods automatically take care of rearranging all the fields. ##### Insert method Add a new item to the array: ```tsx import { insert } from '@formisch/react'; ; ``` The `at` option can be used to specify the index where the item should be inserted. If not provided, the item is added to the end of the array. ##### Remove method Remove an item from the array: ```tsx import { remove } from '@formisch/react'; ; ``` ##### Move method Move an item from one position to another: ```tsx import { move } from '@formisch/react'; ; ``` ##### Swap method Swap two items in the array: ```tsx import { swap } from '@formisch/react'; ; ``` ##### Replace method Replace an item with new data: ```tsx import { replace } from '@formisch/react'; ; ``` #### Nested field arrays If you need to nest multiple field arrays, the path array syntax makes it straightforward. Simply extend the path with additional array indices: ```tsx const NestedSchema = v.object({ categories: v.array( v.object({ name: v.string(), items: v.array( v.object({ title: v.string(), }) ), }) ), }); {(categoryArray) => ( <> {categoryArray.items.map((categoryItem, categoryIndex) => (
{(field) => } {(itemArray) => ( <> {itemArray.items.map((item, itemIndex) => ( {(field) => } ))} )}
))} )}
; ``` You can nest field arrays as deeply as you like. You will also find a suitable example of this in our [playground](/playground/nested/). #### Field array validation As with fields, you can validate field arrays using Valibot's array validation functions. For example, to limit the length of the array: ```tsx const TodoFormSchema = v.object({ todos: v.pipe( v.array( v.object({ label: v.string(), deadline: v.string(), }) ), v.minLength(1), v.maxLength(10) ), }); ``` The validation errors for the field array itself are available in `fieldArray.errors` and can be displayed alongside the array. ### TypeScript Since the library is written in TypeScript and we put a lot of emphasis on the development experience, you can expect maximum TypeScript support. Types are automatically inferred from your [Valibot schemas](/react/guides/define-your-form.md), providing type safety throughout your forms. #### Type inference Formisch uses Valibot's type inference to automatically derive TypeScript types from your schemas. You don't need to define separate types—they're inferred automatically. ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema, }); // TypeScript knows the form structure from the schema // loginForm is of type FormStore return (
{ // output is fully typed based on LoginSchema console.log(output.email); // ✓ Type-safe console.log(output.username); // ✗ TypeScript error }} > {/* Form fields */}
); } ``` ##### Input and output types Valibot schemas can have different input and output types when using transformations. Formisch provides proper typing for both. ```tsx import { Field, Form, useForm } from '@formisch/react'; import * as v from 'valibot'; const ProfileSchema = v.object({ age: v.pipe( v.string(), // Input type: string (from HTML input) v.transform((input) => Number(input)), // Output type: number v.number() ), birthDate: v.pipe( v.string(), // Input type: string (ISO date string) v.transform((input) => new Date(input)), // Output type: Date v.date() ), }); export default function ProfilePage() { const profileForm = useForm({ schema: ProfileSchema, }); return (
{ // output is: { age: number; birthDate: Date } console.log(output.age); // number console.log(output.birthDate); // Date }} > {(field) => ( // field.input is string )} {(field) => ( // field.input is string )}
); } ``` ##### Type-safe paths Field paths are fully type-checked. TypeScript will provide autocompletion and catch invalid paths at compile time. ```tsx const UserSchema = v.object({ profile: v.object({ name: v.object({ first: v.string(), last: v.string(), }), email: v.string(), }), }); const userForm = useForm({ schema: UserSchema }); // ✓ Valid paths - TypeScript provides autocompletion {() => <>{/* ... */}} {() => <>{/* ... */}} // ✗ Invalid paths - TypeScript error {() => <>{/* ... */}} {() => <>{/* ... */}} ``` #### Type-safe props To pass your form to another component via props, you can use the [`FormStore`](/react/api/FormStore.md) type along with your schema type to get full type safety. ```tsx import { Form, type FormStore, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema, }); return ; } type FormContentProps = { of: FormStore; }; function FormContent(props: FormContentProps) { return (
console.log(output)}> {/* Form fields */}
); } ``` #### Generic field components You can create generic field components with proper TypeScript typing using the [`FormStore`](/react/api/FormStore.md) type with Valibot's `GenericSchema`. ```tsx import { type FormStore, useField } from '@formisch/react'; import type { FunctionComponent } from 'react'; import * as v from 'valibot'; type EmailInputProps = { of: FormStore>; }; const EmailInput: FunctionComponent = (props) => { const field = useField(props.of, { path: ['email'] }); return (
{field.errors &&
{field.errors[0]}
}
); }; ``` The `v.GenericSchema<{ email: string }>` type ensures that the form passed to `EmailInput` must have an `email` field of type `string`. TypeScript will catch any type mismatches at compile time. #### Available types Most types you need can be imported from `@formisch/react`. You can find all available types in our [API reference](/react/api/). - [`FormStore`](/react/api/FormStore.md) - The form store type - [`FieldStore`](/react/api/FieldStore.md) - The field store type - [`FieldArrayStore`](/react/api/FieldArrayStore.md) - The field array store type - [`ValidPath`](/core/api/ValidPath.md) - Type for valid field paths - [`ValidArrayPath`](/core/api/ValidArrayPath.md) - Type for valid array field paths - [`FormSchema`](/core/api/FormSchema.md) - Form schema type required at the root - [`Schema`](/core/api/Schema.md) - Base schema type from Valibot - [`SubmitHandler`](/core/api/SubmitHandler.md) - Type for submit handlers without the event - [`SubmitEventHandler`](/core/api/SubmitEventHandler.md) - Type for submit handlers with the event ### Architecture You don't need to read this guide to use Formisch. It's here for people who want to understand why the bundle stays small, why updates are fine-grained, and how the same library can support React, React Native, Angular, SolidJS, Vue, Svelte, Preact, Qwik and HonoX without forking the codebase. Each of those properties falls out of a few deliberate architectural choices. #### Three packages, three responsibilities Formisch is structured as three packages, each with a clear role: - [`@formisch/core`](https://github.com/open-circle/formisch/tree/main/packages/core) is the framework-agnostic foundation. It contains the form and field store types, the recursive store builder that mirrors your Valibot schema, and the validation orchestration. - [`@formisch/methods`](https://github.com/open-circle/formisch/tree/main/packages/methods) exposes the form operations as standalone, tree-shakeable functions: [`setInput`](/methods/api/setInput.md), [`validate`](/methods/api/validate.md), [`reset`](/methods/api/reset.md), [`insert`](/methods/api/insert.md), [`move`](/methods/api/move.md), [`focus`](/methods/api/focus.md) and so on. Each method lives in its own file and only imports the core helpers it actually needs. - [`@formisch/react`](https://github.com/open-circle/formisch/tree/main/frameworks/react) is the thin user-facing layer. It provides the [`useForm`](/react/api/useForm.md), [`useField`](/react/api/useField.md) and [`useFieldArray`](/react/api/useFieldArray.md) hooks, the [`
`](/react/api/Form.md), [``](/react/api/Field.md) and [``](/react/api/FieldArray.md) components, and re-exports every method from `@formisch/methods` so you only import from a single package. ``` @formisch/react ├─ useForm, , , … (React-specific reactive layer) └─ re-exports @formisch/methods/react (focus, reset, validate, …) └─ @formisch/core/react (createFormStore, types, signals) └─ framework adapter (createSignal, batch, untrack, createId) ``` The modular architecture is what makes Formisch tree-shakeable. The core stays small, and every additional capability (`setInput`, `validate`, `reset`, `insert`, `move`, `focus` and the rest) is exported as its own function. A form that only imports `useForm`, `` and `` ships nothing else, even though `@formisch/react` re-exports every method. #### One core, one adapter per framework The core package is framework-agnostic, but it still needs _some_ reactivity primitive to build on. Formisch handles this by providing a subpath export for every supported framework (`@formisch/core/react`, `@formisch/core/solid`, `@formisch/core/vue`, …), all built from the same source. The only file that differs between them [is a small adapter](https://github.com/open-circle/formisch/blob/main/packages/core/src/framework/index.ts) that exports four functions: `createSignal`, `batch`, `untrack` and `createId`. The swap happens at build time, not at runtime. A small [rolldown plugin](https://github.com/open-circle/formisch/blob/main/packages/core/tsdown.config.ts) sits in front of import resolution: whenever the bundler resolves an import of `./framework/index.ts`, the plugin looks for a sibling `./framework/index.react.ts` (or `.solid.ts`, `.vue.ts`, …) and, if it exists, redirects the import there. The build runs once per framework, and each run produces a self-contained bundle with the framework-specific adapter inlined. Since React doesn't have a native signal primitive, [the React adapter](https://github.com/open-circle/formisch/blob/main/packages/core/src/framework/index.react.ts) implements a small pub/sub system from scratch that exposes the `Signal` shape: ```ts export function createSignal(value: T): Signal { const subscribers = new Set(); return { get value() { if (listener) { subscribers.add(listener); listener[1].add(subscribers); } return value; }, set value(newValue: T) { if (newValue !== value) { value = newValue; // notify subscribers … } }, }; } ``` A companion [`useSignals`](https://github.com/open-circle/formisch/blob/main/frameworks/react/src/hooks/useSignals/useSignals.ts) hook in the React wrapper registers your component as a listener and forces a re-render when any signal it read changes. For frameworks that already have native signals (Solid, Preact, Vue, Svelte, Qwik), the adapter is a thin wrapper around the framework's own primitive, sometimes just a single re-export. Every other file in `@formisch/core` only ever imports `createSignal`, `batch`, `untrack` and `createId`, never a framework directly. That's why the same [`createFormStore`](https://github.com/open-circle/formisch/blob/main/packages/core/src/form/createFormStore/createFormStore.ts) code path can power every framework binding without a single conditional. This is what makes Formisch different from most framework-agnostic libraries. The usual approach is to ship a runtime abstraction (a custom store, an observer protocol, a subscription layer) that lives in the bundle and has to be bridged into each framework. Formisch ships nothing like that. Where the framework has native signals, Formisch uses them directly; where it doesn't, the adapter is just enough pub/sub to drive re-renders. Either way, there is no extra layer between your form state and the framework's reactivity, and your bundle pays no overhead for portability. In React, form state lives in the same minimal pub/sub the wrapper already needs to subscribe components, with no second abstraction on top. That Formisch is framework-agnostic is not a trade-off you make. It's a benefit you get. A bug surfaced by a Svelte user is a bug fixed for React, Solid, Vue and everyone else. An improvement to the recursive store builder, the validation orchestration or any individual method lands across every binding at once. There is one library to maintain, not one per framework, and every community pulls the rest forward. #### State lives in signals Every piece of reactive state in Formisch is a [`Signal`](https://github.com/open-circle/formisch/blob/main/packages/core/src/types/signal/signal.ts) with the same minimal interface: ```ts interface Signal { get value(): T; set value(nextValue: T): void; } ``` Reads track, writes notify. There is no central store object that gets diffed and no equality check on the consumer side. Each field carries its own signals for `errors`, `isTouched`, `isEdited`, `isDirty`, plus an `input` signal for value fields and a `children` collection for arrays and objects. When you call `setInput(form, { path: ['email'], input: 'a@b.c' })`, only the `input` signal of that one field is written, so only the components that read that one signal (typically a single ``) re-render. This is the source of the fine-grained reactivity. The shape of the store is pre-allocated at form creation, matching the shape of your Valibot schema, so methods never have to look up paths in a generic object. They walk a typed tree of stores and update individual signals. #### What happens when you call `useForm` When you call [`useForm`](/react/api/useForm.md), three layers cooperate to produce the form store you receive. ```tsx import { useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe(v.string(), v.email()), password: v.pipe(v.string(), v.minLength(8)), }); function LoginForm() { const loginForm = useForm({ schema: LoginSchema }); // … } ``` First, the [React wrapper](https://github.com/open-circle/formisch/blob/main/frameworks/react/src/hooks/useForm/useForm.ts) hands the configuration to the core function [`createFormStore`](https://github.com/open-circle/formisch/blob/main/packages/core/src/form/createFormStore/createFormStore.ts) inside a `useMemo`, together with a parse closure that captures your schema: ```ts const internalFormStore = useMemo( () => createFormStore(config, (input) => v.safeParseAsync(config.schema, input)), [] ); ``` Next, `createFormStore` calls [`initializeFieldStore`](https://github.com/open-circle/formisch/blob/main/packages/core/src/field/initializeFieldStore/initializeFieldStore.ts), which walks your Valibot schema recursively and builds the internal store hierarchy: - A `v.object(...)` becomes an `InternalObjectStore` with a `children` record keyed by field name. - A `v.array(...)` or `v.tuple(...)` becomes an `InternalArrayStore` with a `children` list and its own `initialInput`, `startInput` and `input` signals so it can track structural changes. - A leaf like `v.string()` or `v.number()` becomes an `InternalValueStore` with an `input` signal that holds the current field value. - Wrapper schemas such as `v.optional`, `v.nullable`, `v.nonNullable` and `v.lazy` are unwrapped and recursed into. - `v.union`, `v.variant` and `v.intersect` initialize every option into the same store, which is what lets you address discriminated fields with a single field path. At every level, the same four signals are created: `errors`, `isTouched`, `isEdited` and `isDirty`. Once the field tree is built, three more signals are added to the form root: `isSubmitting`, `isSubmitted` and `isValidating`. Finally, the React wrapper builds the public form store you actually receive. It's a small object that sits on top of the internal store: form-level signals are exposed through getters that read `internalFormStore.isSubmitting.value` and friends, while derived state like `isTouched`, `isEdited`, `isDirty` and `isValid` is computed on demand from the field tree. The whole object is memoized so it survives re-renders: ```ts return useMemo( () => ({ [INTERNAL]: internalFormStore, get isSubmitting() { return internalFormStore.isSubmitting.value; }, get isTouched() { return getFieldBool(internalFormStore, 'isTouched'); }, // … }), [internalFormStore] ); ``` At the very top of the hook body, before any of this, the wrapper calls `useSignals()` to bridge the signals into React's render cycle: it registers the component as a listener so any signal read by the getters above will trigger a re-render when it changes. The internal store is tucked away behind the [`INTERNAL`](https://github.com/open-circle/formisch/blob/main/packages/core/src/values.ts) key. Methods like `setInput(form, …)` reach in via `form[INTERNAL]` to mutate signals, while regular form code uses the public form store. This separation is what keeps the public API small and stable even as the internal shape evolves. #### Why this design pays off Bundle size is the obvious payoff. The others are why the design is worth talking about: - **Small bundle size.** Because methods are individual modules re-exported from [`@formisch/react`](https://github.com/open-circle/formisch/tree/main/frameworks/react), a form that uses only [`useForm`](/react/api/useForm.md) and [``](/react/api/Field.md) never pulls in [`validate`](/methods/api/validate.md), [`reset`](/methods/api/reset.md), [`insert`](/methods/api/insert.md) or the other operations. Tree-shaking gets to do real work. - **Fine-grained reactivity.** The store shape is pre-allocated at form creation, with one signal per piece of state. Methods write `.value` directly, and only the components subscribed to that specific signal re-render. Updating one field does not invalidate the rest. - **Framework portability.** The entire library is parameterized over a four-function adapter. Adding a new framework means writing a small adapter that maps `createSignal`, `batch`, `untrack` and `createId` onto its primitives. - **Type safety.** Your Valibot schema is the single source of truth. It drives both runtime parsing and the inferred TypeScript types for paths, inputs and outputs, so there is no second declaration to keep in sync. #### Build on the core Use `@formisch/react/internals` to access the framework-specific core from your application or library. The [internals guide](/react/guides/internals.md) shows how to create custom methods and explains what to consider when building reactive bindings and components. #### Further reading To see how these design choices stack up against React Hook Form and TanStack Form, head to the [comparison](/react/guides/comparison.md) guide. For a closer look at how Valibot's inference flows into your editor, see [TypeScript](/react/guides/typescript.md). And if you want to read the recursive walker, the adapter implementations, or how individual methods are written, the full source is on [GitHub](https://github.com/open-circle/formisch). ### Internals Formisch exposes its core through `@formisch/react/internals`. You can use these functions and types to build methods, reactive bindings and components for behavior that Formisch does not provide out of the box. Coding agents can use the same building blocks as the library itself. #### Versioning **Internals are not covered by Formisch's semantic versioning guarantees.** Breaking changes to their functions, types and store structure can occur in any release, including minor and patch releases. Review your use of internals when upgrading Formisch, and test validation, reactivity and cleanup for the behavior your extension implements. #### Import the core ```ts import { type BaseFormStore, getFieldStore, INTERNAL, setFieldInput, } from '@formisch/react/internals'; ``` This entry point re-exports the entire React-specific core, including store types, field and array helpers, validation utilities and the reactivity adapter. It is included in `@formisch/react`, so no additional package is needed. Always use the internals from the same framework package as your form so they share its reactivity implementation. The regular `@formisch/react` entry point provides the ready-made methods and framework bindings. The internals entry point gives you access to the lower-level operations and store structure described in the [architecture guide](/react/guides/architecture.md). #### Implement a method The existing [`setInput`](/methods/api/setInput.md) method shows how these building blocks work together. This simplified implementation updates a single field and reuses `SetFieldInputConfig` to infer the path and input types from your schema: ```ts import type { SetFieldInputConfig } from '@formisch/react'; import { type BaseFormStore, batch, type FormSchema, getFieldStore, INTERNAL, type RequiredPath, setFieldInput, validateIfRequired, } from '@formisch/react/internals'; /** * Sets a field's input and validates it if required. */ export function setInput< TSchema extends FormSchema, TFieldPath extends RequiredPath, >( form: BaseFormStore, config: SetFieldInputConfig ): void { batch(() => { const internalFormStore = form[INTERNAL]; const internalFieldStore = getFieldStore(internalFormStore, config.path); if (internalFieldStore) { setFieldInput(internalFormStore, config.path, config.input); validateIfRequired(internalFormStore, internalFieldStore, 'input'); } }); } ``` Pass an existing form store, a field path and its new input to this method: ```ts setInput(loginForm, { path: ['email'], input: 'jane@example.com' }); ``` `INTERNAL` is the key for accessing the internal store through `form[INTERNAL]`. `getFieldStore` can return `undefined` when a dynamic array item no longer exists, so check the result before updating the field. `setFieldInput` updates the input and maintains touched, edited and dirty state. Writing directly to an input signal bypasses this bookkeeping. `batch` groups signal updates, and `validateIfRequired` triggers validation only when the form's validation settings require it for an input event. The [full implementation](https://github.com/open-circle/formisch/blob/main/packages/methods/src/setInput/setInput.ts) also supports setting the entire form input and includes the corresponding type overloads. Use the built-in method in your application; this example is a starting point for understanding the core helpers and building your own methods. #### Build reactive bindings and components You can also build your own framework bindings on top of the core. These bindings are responsible for subscribing to state changes, registering input elements or refs, handling events and cleaning up when fields unmount. Start with [input components](/react/guides/input-components.md) if you can compose the existing bindings. Reading a core signal alone does not subscribe a React component. The existing hooks use the internal `useSignals` hook to manage subscriptions and cleanup. Compose the public hooks where possible, or follow that implementation when building your own subscription layer. The [React binding source](https://github.com/open-circle/formisch/tree/main/frameworks/react/src) shows how Formisch handles these responsibilities. The core exposes the helpers those bindings use; it does not automatically supply their framework lifecycle behavior. #### Work with coding agents Give your agent this guide, your schema and the behavior you want to build. Ask it to inspect the relevant method or framework binding and the installed type declarations, then test the custom behavior with your form. The [coding agents guide](/react/guides/coding-agents.md) explains how to access the documentation through our skill, MCP server and Markdown files. ## Migration guides (guides) ### Migrate from React Hook Form This guide walks you through migrating your forms from [React Hook Form](https://react-hook-form.com) to Formisch. It covers the mental-model shift, a complete side-by-side example, a step-by-step migration path, and a mapping of React Hook Form APIs to their Formisch equivalents. Migrating is a rewrite of the form layer, not a drop-in replacement. The mental model is different: instead of starting from a component and attaching form behavior to it, you start from a Valibot schema and build the component around it. The good news is that forms are naturally isolated units, so the rewrite happens one form at a time. Both libraries can coexist in the same application without conflicts. You can install Formisch next to React Hook Form, migrate a single form, and remove React Hook Form once the last one is converted. Since both libraries export a hook named `useForm`, the import path determines which one a component uses. #### Key differences React Hook Form is component-first. You declare a TypeScript generic for your form values, register inputs by string name, and attach validation either as per-field rules or through a resolver. Formisch is schema-first: a single Valibot schema is the source of types, validation rules, and form structure all at once. There is no separate generic to declare and no `defaultValues` object to keep aligned with your validation. The most important differences at a glance: - **Type source**: React Hook Form types come from a generic you declare on `useForm()`. Formisch infers all types, including field paths and the validated output, from the schema. - **Validation location**: React Hook Form spreads validation across `register` rules, `Controller` rules, or a resolver. Formisch defines all validation in the schema, next to the structure it validates. - **Validation timing**: React Hook Form uses the `mode` and `reValidateMode` options. Formisch uses the equivalent `validate` and `revalidate` options with slightly different mode names. - **Validation scope**: React Hook Form validates individual fields as they trigger. Formisch always parses the entire form against the schema in a single pass and distributes the resulting errors to the individual fields. Cross-field rules work without extra wiring, and each field still only re-renders when its own errors change. - **Reactivity**: React Hook Form makes re-render scope your responsibility through `watch`, `useWatch`, and the `formState` Proxy with its destructuring rules. Formisch is built on fine-grained signals, so components automatically re-render when the state they read changes. There is no subscription API to manage. - **Field binding**: React Hook Form registers inputs by string name (`register('user.email')`). Formisch connects fields through the headless [`Field`](/react/api/Field.md) component with a type-safe path array (`path={['user', 'email']}`). If you already validate with `valibotResolver` from `@hookform/resolvers`, you are halfway there: your Valibot schema carries over to Formisch unchanged. #### Side-by-side example The following login form has two validated fields, displays error messages, disables the submit button while submitting, and processes the values on submission. Both versions implement identical behavior. ##### React Hook Form ```tsx import { type SubmitHandler, useForm } from 'react-hook-form'; interface LoginValues { email: string; password: string; } export default function LoginPage() { const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm({ defaultValues: { email: '', password: '' }, }); const onSubmit: SubmitHandler = async (values) => { // Process the validated form values console.log(values); }; return ( {errors.email &&
{errors.email.message}
} {errors.password &&
{errors.password.message}
} ); } ``` ##### Formisch ```tsx import { Field, Form, type SubmitHandler, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema }); const onSubmit: SubmitHandler = async (values) => { // Process the validated form values console.log(values); }; return (
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
); } ``` Notice how the validation rules moved out of the JSX and into the schema, and how the `LoginValues` interface disappeared because the schema provides the types. Error messages live on each field store instead of a central `errors` object. #### Migration steps ##### Install Formisch Add Formisch and Valibot alongside React Hook Form. Both form libraries can run in parallel during the migration. ```bash npm install @formisch/react valibot ``` See the [installation](/react/guides/installation.md) guide for other package managers. ##### Move validation into a Valibot schema Translate your `register` rules or resolver schema into a single Valibot schema. Most rules have a close counterpart: `required` becomes `v.nonEmpty()` for strings and arrays, `minLength` becomes `v.minLength()`, and `pattern` usually becomes a dedicated action like `v.email()` or `v.regex()`. Use a type-appropriate schema to express requiredness for other inputs. ```ts import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); ``` If you already use `valibotResolver`, reuse your existing schema as-is. Define fields in the same order they appear in your form, because Formisch focuses the first field with an error on a failed submit. The [define your form](/react/guides/define-your-form.md) guide covers schema design in detail. ##### Replace the form setup Swap React Hook Form's `useForm` for the Formisch [`useForm`](/react/api/useForm.md) hook. The generic and the resolver disappear, and the schema takes their place. `defaultValues` becomes `initialInput` and is optional: required string fields start as an empty string automatically, so you no longer need to list every field just to avoid `undefined` values. ```tsx // Before import { useForm } from 'react-hook-form'; const { register, handleSubmit, formState } = useForm({ resolver: valibotResolver(LoginSchema), defaultValues: { email: '', password: '' }, mode: 'onTouched', }); ``` ```tsx // After import { useForm } from '@formisch/react'; const loginForm = useForm({ schema: LoginSchema, validate: 'blur', revalidate: 'input', }); ``` The `mode` and `reValidateMode` options map to `validate` and `revalidate`. See the [validation timing](#validation-timing) section below for the exact mapping. ##### Replace field bindings Replace each `register` call with the [`Field`](/react/api/Field.md) component. Instead of spreading `register('email')`, you spread `field.props` onto the input and bind `field.input` as its value. Errors move from the central `formState.errors` object to the field store, so the error display lives right next to the input. ```tsx // Before <> {errors.email &&
{errors.email.message}
} ``` ```tsx // After {(field) => (
{field.errors &&
{field.errors[0]}
}
)}
``` String paths with dots become type-safe path arrays: `register('user.email')` turns into `path={['user', 'email']}` and `register('todos.0.label')` turns into `path={['todos', 0, 'label']}`. Where you used `Controller` or `useController` for individual field components, use the [`Field`](/react/api/Field.md) component or [`useField`](/react/api/useField.md) hook instead. The [add form fields](/react/guides/add-form-fields.md) guide explains both in detail. ##### Update submission handling Replace the `
` element wrapped with `handleSubmit(onSubmit)` by the [`Form`](/react/api/Form.md) component. Your handler keeps the same shape: it only runs after validation succeeds and receives the validated values, which are now typed as the schema's output. ```tsx // Before {/* fields */}
// After
{/* fields */}
``` Async handlers work the same way, and `loginForm.isSubmitting` replaces `formState.isSubmitting` for the loading state. See the [handle submission](/react/guides/handle-submission.md) guide for details. #### API mapping | React Hook Form | Formisch | | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `useForm(config)` | [`useForm`](/react/api/useForm.md) with `schema` (types are inferred) | | `resolver: valibotResolver(schema)` | `schema` option | | `defaultValues` | `initialInput` option | | `mode` / `reValidateMode` | `validate` / `revalidate` options | | `register('name')` | [`Field`](/react/api/Field.md) component with `path={['name']}` | | `Controller` / `useController` | [`useField`](/react/api/useField.md) hook or `field.onChange` | | `handleSubmit(onValid)` | `onSubmit` prop of [`Form`](/react/api/Form.md) or [`handleSubmit`](/methods/api/handleSubmit.md) | | `formState.errors` | `field.errors` per field, [`getErrors`](/methods/api/getErrors.md), [`getDeepErrors`](/methods/api/getDeepErrors.md) | | `formState.isDirty` / `dirtyFields` | `form.isDirty`, `field.isDirty`, [`getDirtyInput`](/methods/api/getDirtyInput.md) | | `formState.touchedFields` | `field.isTouched` | | `formState.isSubmitting` | `form.isSubmitting` | | `formState.isSubmitted` | `form.isSubmitted` | | `formState.isValid` | `form.isValid` | | `formState.isValidating` | `form.isValidating` | | `watch('name')` / `useWatch` | `field.input`, [`getInput`](/methods/api/getInput.md) | | `getValues()` | [`getInput`](/methods/api/getInput.md) | | `setValue` | [`setInput`](/methods/api/setInput.md) | | `setError` / `clearErrors` | [`setErrors`](/methods/api/setErrors.md) | | `trigger` | [`validate`](/methods/api/validate.md) | | `setFocus` | [`focus`](/methods/api/focus.md) | | `reset` / `resetField` | [`reset`](/methods/api/reset.md) | | `useFieldArray` | [`FieldArray`](/react/api/FieldArray.md) component or [`useFieldArray`](/react/api/useFieldArray.md) hook | | `append` / `prepend` / `insert` | [`insert`](/methods/api/insert.md) | | `remove` / `move` / `swap` / `update` | [`remove`](/methods/api/remove.md), [`move`](/methods/api/move.md), [`swap`](/methods/api/swap.md), [`replace`](/methods/api/replace.md) | | `FormProvider` / `useFormContext` | Not needed (see notes) | | `unregister` / `shouldUnregister` | No equivalent (see notes) | A few entries deserve extra context: - **`FormProvider` / `useFormContext`**: The Formisch form store is a plain object. Pass it down as a prop, as our [input components](/react/guides/input-components.md) do, or share it through your own React context if you prefer. - **`unregister` / `shouldUnregister`**: In Formisch, the schema defines which fields exist, independent of what is currently mounted. For conditional form shapes, model the variants in the schema, for example with `v.optional` or `v.variant`. - **`watch` callbacks and subscriptions**: There is no subscription API because none is needed. Reading `field.input` or any form state during render is automatically reactive. - **`trigger('name')`**: The [`validate`](/methods/api/validate.md) method always validates the entire form against the schema. The results are still distributed per field, so field-level triggering is not necessary. - **`shouldFocusError`**: Formisch focuses the first field with an error automatically when a submit fails, following the field order of your schema. - **`formState.isValid`**: In Formisch, `form.isValid` reflects the result of the last validation run. With the default `validate: 'submit'` timing it stays `true` until the first submit, unlike React Hook Form's `isValid`, which validates proactively. If you rely on it before the first submit, for example to disable the submit button, set `validate: 'initial'`. - **`formState.touchedFields`**: Formisch marks a field as touched when it receives focus or its input is set, while React Hook Form marks it on blur. During ordinary keyboard interaction that means touched-based logic usually reacts on focus instead of waiting for blur. Formisch's `setInput` also marks the field as touched and edited; React Hook Form's `setValue` only updates those flags when `shouldTouch` or `shouldDirty` is enabled. #### Common patterns ##### Form state React Hook Form exposes form state through the `formState` Proxy, which requires you to destructure the properties you use so the subscription is set up correctly. In Formisch, you read state directly from the form store. Reads are tracked through signals, so components re-render automatically and only when the state they read changes. ```tsx // Before const { formState: { isDirty, isSubmitting }, } = useForm(); ; // After const profileForm = useForm({ schema: ProfileSchema }); ; ``` ##### Validation timing React Hook Form's `mode` and `reValidateMode` map to Formisch's `validate` and `revalidate`. The Formisch modes are named after DOM events: `'input'` fires on every keystroke and is what React Hook Form calls `onChange`. A separate `'change'` mode exists, but because React emits its change event on every keystroke for text inputs, both behave the same in React, so prefer `'input'`. There are also more options like `'touch'` and `'initial'`. ```tsx // Before const form = useForm({ resolver: valibotResolver(Schema), mode: 'onTouched', reValidateMode: 'onChange', }); // After: first validation on blur, revalidation on every keystroke const form = useForm({ schema: Schema, validate: 'blur', revalidate: 'input', }); ``` The defaults are already close: Formisch validates on submit first and revalidates on input, similar to React Hook Form's `onSubmit` mode with `onChange` revalidation. See the [validation](/react/guides/validation.md) guide for all modes and for showing errors at the right time. ##### Field arrays React Hook Form's `useFieldArray` returns `fields` with stable `id` keys plus mutation functions. Formisch provides the [`FieldArray`](/react/api/FieldArray.md) component, whose `items` array contains unique string identifiers to use as keys, and standalone methods like [`insert`](/methods/api/insert.md) and [`remove`](/methods/api/remove.md). ```tsx // Before const { fields, append, remove } = useFieldArray({ control, name: 'todos' }); <> {fields.map((item, index) => (
))} ; ``` ```tsx // After import { Field, FieldArray, insert, remove } from '@formisch/react'; {(fieldArray) => (
{fieldArray.items.map((item, index) => (
{(field) => }
))}
)}
; ``` Unlike `append` and `prepend`, the single `insert` method covers all positions through its optional `at` option. See the [field arrays](/react/guides/field-arrays.md) guide for moving, swapping, and validating arrays. ##### Reset React Hook Form's `reset()` restores `defaultValues`, and `reset(values)` replaces them. The Formisch [`reset`](/methods/api/reset.md) method works the same way with its config object, and it also resets individual fields through the `path` option, replacing `resetField`. ```tsx import { reset } from '@formisch/react'; // Reset the entire form to its initial input reset(profileForm); // Reset with new initial input, e.g. after refetching server data reset(profileForm, { initialInput: { name: 'Jane' } }); // Reset a single field reset(profileForm, { path: ['email'] }); ``` As in React Hook Form, resetting updates the baseline for dirty tracking. Fields you plan to reset programmatically must be controlled, so bind `value` or `checked` as described in the [controlled fields](/react/guides/controlled-fields.md) guide. ##### Special inputs React Hook Form's `register` detects checkboxes, radio buttons, and selects through the input's ref. In Formisch, you spread `field.props` and bind the state attribute that matches the input type, for example `checked` for a checkbox: ```tsx {(field) => ( )} ``` Where you used `register('age', { valueAsNumber: true })`, note that Formisch reads DOM values as strings. Fields with a `v.number()` or `v.date()` schema convert the value in a controlled change handler instead, as shown in the [controlled fields](/react/guides/controlled-fields.md) guide. For component libraries where you previously reached for `Controller`, pass `field.input` and `field.onChange` directly to the component. The [special inputs](/react/guides/special-inputs.md) guide covers checkboxes, radio buttons, selects, and file inputs in detail. #### Next steps You now have everything you need to migrate your forms. Start with the [define your form](/react/guides/define-your-form.md) and [create your form](/react/guides/create-your-form.md) guides to deepen the schema-first workflow, build reusable [input components](/react/guides/input-components.md) to keep your migrated forms tidy, and explore the [form methods](/react/guides/form-methods.md) guide for everything that replaces React Hook Form's imperative API. ### Migrate from TanStack Form This guide walks you through migrating your React forms from [TanStack Form](https://tanstack.com/form/latest) to Formisch. It explains the mental-model shift, shows the same form in both libraries side by side, breaks the migration into small steps, and maps common TanStack Form APIs to their Formisch equivalents. Migrating is a rewrite of the form layer, not a drop-in replacement. The component structure often stays similar, but the way you define types, validation, and state access changes. The good news: TanStack Form supports Standard Schema validators, so if you already validate with [Valibot](https://valibot.dev), your schemas carry over unchanged. Both libraries can coexist in the same application without conflicts. You can migrate one form at a time and remove `@tanstack/react-form` once the last form has been converted. Since both libraries export a hook named `useForm`, the import path determines which one a component uses. #### Key differences TanStack Form starts from a state container: you declare `defaultValues`, TypeScript infers the form's types from them, and you attach validators to the form or to individual fields, each with its own trigger like `onChange`, `onBlur`, or `onSubmit`. Reactivity is subscription-based: you opt into re-renders with `form.Subscribe` or `useStore` selectors. Formisch starts from a schema: a single Valibot schema is the source of types, validation rules, and form structure at once. There is no `defaultValues` object to keep aligned with your types and no per-field validator configuration. Validation always parses the entire form against the schema, so cross-field rules work without extra wiring, and its timing is controlled form-wide with the `validate` and `revalidate` config. Reactivity is built on fine-grained signals wired into React's render cycle, so you read state directly from the form store and only the components that depend on it re-render. In practice, the migration boils down to these changes: - **Types**: Inferred from the schema instead of from `defaultValues`. - **Validation**: Defined once in the schema instead of spread across `validators` configs; timing moves from per-validator triggers to the form-wide `validate` and `revalidate` options. - **Field addressing**: Path arrays like `['todos', 0, 'label']` instead of interpolated string names like `` `todos[${index}].label` ``. - **Field binding**: Spreading `field.props` instead of manually wiring `value`, `onChange`, and `onBlur`. - **State access**: Reading the form store directly instead of subscribing with selectors. - **Errors**: Plain string arrays in `field.errors` instead of issue objects in `field.state.meta.errors`. #### Side-by-side example The following login form validates an email and a password and logs the values on submission. Both versions use the exact same Valibot schema, which TanStack Form accepts as a Standard Schema validator. ##### TanStack Form ```tsx import { useForm } from '@tanstack/react-form'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); export default function LoginPage() { const form = useForm({ defaultValues: { email: '', password: '', }, validators: { onChange: LoginSchema, }, onSubmit: async ({ value }) => { console.log(value); }, }); return (
{ event.preventDefault(); event.stopPropagation(); form.handleSubmit(); }} > {(field) => (
field.handleChange(event.target.value)} onBlur={field.handleBlur} type="email" /> {!field.state.meta.isValid && (
{field.state.meta.errors[0]?.message}
)}
)}
{(field) => (
field.handleChange(event.target.value)} onBlur={field.handleBlur} type="password" /> {!field.state.meta.isValid && (
{field.state.meta.errors[0]?.message}
)}
)}
state.isSubmitting}> {(isSubmitting) => ( )}
); } ``` ##### Formisch ```tsx import { Field, Form, useForm } from '@formisch/react'; import type { SubmitHandler } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema, }); const submitForm: SubmitHandler = async (values) => { console.log(values); }; return (
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
); } ``` Notice what disappeared: the `defaultValues` object (required string fields start as `''` automatically), the manual `value`, `onChange`, and `onBlur` wiring (replaced by spreading `field.props`), the `event.preventDefault()` boilerplate (the [`Form`](/react/api/Form.md) component handles it), and the `form.Subscribe` wrapper around the submit button (`loginForm.isSubmitting` is read directly). One timing difference: the TanStack Form version validates on every change from the start, while Formisch by default waits until the first submit and then revalidates on every input. Pass `validate: 'input'` to [`useForm`](/react/api/useForm.md) if you want to match the TanStack Form behavior. #### Migration steps ##### Install Formisch Install Formisch and Valibot alongside your existing setup. Both form libraries can run in the same app during the migration. ```bash npm install @formisch/react valibot ``` See the [installation](/react/guides/installation.md) guide for other package managers and TypeScript requirements. ##### Move validation into a Valibot schema If your form already passes a Valibot schema to `validators`, you can reuse it as is. If you use another Standard Schema library like Zod, or hand-written validator functions attached to fields, rewrite the rules as a single Valibot schema. Each field-level validator becomes a validation rule in the schema: ```ts import * as v from 'valibot'; // Before: onChange: ({ value }) => (!value ? 'Please enter your email.' : undefined) // After: defined once in the schema const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe(v.string(), v.nonEmpty(), v.minLength(8)), }); ``` Define the fields in the same order they appear in your form, because Formisch focuses the first field with an error after a failed submission. See the [define your form](/react/guides/define-your-form.md) guide for details. ##### Replace the form setup Swap the `useForm` import from `@tanstack/react-form` to `@formisch/react` and pass your schema instead of `defaultValues` and `validators`. The `onSubmit` option moves out of the hook (see below). If your `defaultValues` contained real data instead of empty placeholders, pass it as `initialInput`: ```tsx import { useForm } from '@formisch/react'; const loginForm = useForm({ schema: LoginSchema, initialInput: { email: 'user@example.com', }, }); ``` Required string fields start as `''` automatically, so you no longer need to list every field just to initialize it. See the [create your form](/react/guides/create-your-form.md) guide for all configuration options. ##### Replace field bindings Replace each `form.Field` with the [`Field`](/react/api/Field.md) component. String names become path arrays, and the manual event wiring becomes a spread of `field.props`: ```tsx import { Field } from '@formisch/react'; {(field) => (
{field.errors &&
{field.errors[0]}
}
)}
; ``` `field.state.value` becomes `field.input`, and `field.state.meta.errors` becomes `field.errors`, which is either `null` or a non-empty array of strings, so no `.message` access is needed. For nested fields, `name="user.email"` becomes `path={['user', 'email']}` with full autocompletion from your schema. If you extracted fields into their own components, use the [`useField`](/react/api/useField.md) hook instead, as shown in the [add form fields](/react/guides/add-form-fields.md) guide. ##### Update submission handling Replace the native `
` element and its `handleSubmit` boilerplate with the [`Form`](/react/api/Form.md) component. Your `onSubmit` option becomes a handler passed to `Form`, and it receives the validated output of your schema, fully typed by [`SubmitHandler`](/core/api/SubmitHandler.md): ```tsx import { Form } from '@formisch/react'; import type { SubmitHandler } from '@formisch/react'; const submitForm: SubmitHandler = async (values) => { await fetch('/api/login', { method: 'POST', body: JSON.stringify(values), }); }; {/* fields */} ; ``` `event.preventDefault()` is called automatically, and the handler only runs when the form input passes your schema. See the [handle submission](/react/guides/handle-submission.md) guide for async patterns and submitting without a `
` element. #### API mapping | TanStack Form | Formisch | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `useForm({ defaultValues, validators })` | [`useForm`](/react/api/useForm.md) with `schema` | | `defaultValues` | `initialInput` (optional, types come from the schema) | | `onSubmit` option of `useForm` | `onSubmit` prop of [`Form`](/react/api/Form.md) | | `` element + `form.handleSubmit()` | [`Form`](/react/api/Form.md) component | | `form.Field` with `name="user.email"` | [`Field`](/react/api/Field.md) with `path={['user', 'email']}` | | `field.state.value` | `field.input` | | `field.handleChange`, `field.handleBlur` | Spread `field.props`, or `field.onChange` for custom inputs | | `field.state.meta.errors` | `field.errors` | | `field.state.meta.isTouched` | `field.isTouched` | | `field.state.meta.isDirty` | `field.isEdited` (see below) | | `field.state.meta.isDefaultValue` | `!field.isDirty` (see below) | | `form.Subscribe`, `useStore(form.store)` | Read the form store directly (e.g. `form.isSubmitting`, `form.isDirty`) | | `state.canSubmit` | No direct equivalent (see below) | | `form.state.values` | [`getInput`](/methods/api/getInput.md) | | `form.setFieldValue(name, value)` | [`setInput`](/methods/api/setInput.md) | | `form.reset()` | [`reset`](/methods/api/reset.md) | | `form.Field` with `mode="array"` | [`FieldArray`](/react/api/FieldArray.md) or [`useFieldArray`](/react/api/useFieldArray.md) | | `pushValue`, `insertValue` | [`insert`](/methods/api/insert.md) | | `removeValue`, `moveValue` | [`remove`](/methods/api/remove.md), [`move`](/methods/api/move.md) | | `swapValues`, `replaceValue` | [`swap`](/methods/api/swap.md), [`replace`](/methods/api/replace.md) | | `createFormHook`, `useAppForm` | No equivalent needed (see below) | | `asyncDebounceMs` | No direct equivalent (see below) | A few entries deserve a short note: - **`state.canSubmit`**: Formisch does not compute a combined "can submit" flag. The idiomatic pattern is to keep the submit button enabled and let submission trigger validation, which focuses the first invalid field. If you want a validity-based flag, `form.isValid` reflects the result of the last validation run. With the default `validate: 'submit'` timing it stays `true` until the first submit, so combine it with `validate: 'initial'` if you want TanStack-like behavior. - **Dirty state** is split differently. TanStack Form's `isDirty` stays `true` once a field was changed, even if the value is reverted. That matches Formisch's `isEdited`. Formisch's `isDirty` compares the current input against the initial input and turns back off when they match, like TanStack Form's `isDefaultValue` inverted. - **`createFormHook` and `useAppForm`**: These exist in TanStack Form to pre-bind typed field components and share form configuration. Formisch does not need them, since every hook and component is already fully typed by your schema. The role of pre-bound field components is filled by regular [input components](/react/guides/input-components.md). - **`asyncDebounceMs`**: Formisch has no built-in debounce option. Async rules live in the schema via `v.pipeAsync` and `v.checkAsync`, and `form.isValidating` is `true` while they run. See the [validation](/react/guides/validation.md) guide. #### Common patterns ##### Form state In TanStack Form you subscribe to state with a selector to control re-renders, either through `form.Subscribe` (as with the submit button in the side-by-side example above) or with the `useStore` hook in component logic. In Formisch you read the form store directly. The store is built on fine-grained signals wired into React's render cycle, so components re-render only when the properties they read change, without selectors: ```tsx ``` The form store exposes `isSubmitting`, `isSubmitted`, `isValidating`, `isTouched`, `isEdited`, `isDirty`, `isValid`, and `errors`. To read field values in component logic, use the [`getInput`](/methods/api/getInput.md) method, which also stays reactive inside components. ##### Validation timing TanStack Form couples timing to each validator: the key you register a rule under (`onChange`, `onBlur`, `onSubmit`, `onMount`) decides when it runs. In Formisch, the rules live in the schema and timing is configured once for the whole form: ```tsx const loginForm = useForm({ schema: LoginSchema, validate: 'blur', revalidate: 'input', }); ``` The `validate` option controls when a field is first validated (`'initial'`, `'touch'`, `'input'`, `'change'`, `'blur'`, or `'submit'`), and `revalidate` controls when it is checked again after it has an error or the form was submitted. As a rough mapping, `validators.onSubmit` corresponds to `validate: 'submit'` (the default), `validators.onBlur` to `validate: 'blur'`, `validators.onChange` to `validate: 'input'`, and `validators.onMount` to `validate: 'initial'`. Unlike TanStack Form, every validation pass parses the entire schema, so cross-field rules stay correct no matter which field triggered it. The [validation](/react/guides/validation.md) guide covers this in depth, including how to show errors only at the right time. ##### Field arrays In TanStack Form you set `mode="array"` on a field, map over `field.state.value`, and address items with interpolated string names: ```tsx {(todosField) => (
{todosField.state.value.map((_, index) => ( {(field) => ( field.handleChange(event.target.value)} /> )} ))}
)}
``` In Formisch you use the [`FieldArray`](/react/api/FieldArray.md) component and standalone methods. The `items` array contains stable unique IDs to use as keys, so React correctly tracks items when they are added, moved, or removed: ```tsx import { Field, FieldArray, insert } from '@formisch/react'; {(fieldArray) => (
{fieldArray.items.map((item, index) => ( {(field) => } ))}
)}
; ``` The [`insert`](/methods/api/insert.md), [`remove`](/methods/api/remove.md), [`move`](/methods/api/move.md), [`swap`](/methods/api/swap.md), and [`replace`](/methods/api/replace.md) methods cover the operations of `pushValue`, `removeValue`, `moveValue`, `swapValues`, and `replaceValue`. For example, `todosField.removeValue(index)` becomes `remove(todoForm, { path: ['todos'], at: index })`. Rules like a minimum or maximum number of items move into the schema, for example `v.pipe(v.array(…), v.maxLength(10))`. See the [field arrays](/react/guides/field-arrays.md) guide for the full picture. ##### Reset Where TanStack Form offers `form.reset()` to restore `defaultValues`, Formisch provides the [`reset`](/methods/api/reset.md) method, which can also target individual fields or update the baseline: ```tsx import { reset } from '@formisch/react'; // Reset the entire form to its initial input reset(loginForm); // Reset a single field reset(loginForm, { path: ['email'] }); // Reset with a new initial input (e.g. refreshed server data) reset(loginForm, { initialInput: { email: 'jane@example.com' } }); ``` Passing `initialInput` updates the dirty-tracking baseline, which is the right tool when server data changes. Use [`setInput`](/methods/api/setInput.md) instead when you only want to change the current value. ##### Special inputs In TanStack Form, checkboxes, selects, and files are wired manually, for example with `field.handleChange(event.target.checked)`. In Formisch, spreading `field.props` covers all native input types; you only set the state attribute that matches the input: ```tsx {(field) => ( )} ``` See the [special inputs](/react/guides/special-inputs.md) guide for radio groups, multi-selects, and file inputs. One caveat carried over from the DOM: event handlers read strings, so fields with a non-string schema like `v.number()` or `v.date()` need to be controlled, as explained in the [controlled fields](/react/guides/controlled-fields.md) guide. This replaces patterns like `field.handleChange(event.target.valueAsNumber)`. #### Next steps You now have everything you need to convert your forms one by one. To deepen your understanding of the Formisch side, read the [define your form](/react/guides/define-your-form.md) and [add form fields](/react/guides/add-form-fields.md) guides, explore the [form methods](/react/guides/form-methods.md) for programmatic control, and check out the [TypeScript](/react/guides/typescript.md) guide to get the most out of schema-based type inference. ### Migrate from Formik This guide walks you through migrating your forms from [Formik](https://formik.org) to Formisch. It covers the mental-model shift, a complete side-by-side example, a step-by-step migration path, and a mapping of Formik APIs to their Formisch equivalents. Migrating is a rewrite of the form layer, not a drop-in replacement. The mental model shifts: instead of starting from an `initialValues` object and attaching validation to it, you start from a Valibot schema that provides values, types, and validation at once. The good news is that forms are naturally isolated units, so the rewrite happens one form at a time. Both libraries can coexist in the same application without conflicts. You can install Formisch next to Formik, migrate a single form, and remove Formik once the last one is converted. Since both libraries export `Field`, `Form`, `FieldArray`, and `useField`, the import path determines which ones a component uses. #### Key differences Formik is values-first. You declare an `initialValues` object, TypeScript infers your form's types from it, and validation is attached separately through a `validationSchema` written with [Yup](https://github.com/jquense/yup), a `validate` function, or `validate` props on individual fields. All form state lives in a single React state object and reaches your inputs through render props or context. Formisch is schema-first: a single Valibot schema is the source of types, validation rules, and form structure all at once. There is no separate `initialValues` object to keep aligned with your validation, and state is read directly from a signal-based form store. The most important differences at a glance: - **Type source**: Formik infers types from `initialValues`, and your Yup schema is typed separately. Formisch infers all types, including field paths and the validated output, from the schema. - **Validation location**: Formik spreads validation across `validationSchema`, the `validate` function, and field-level `validate` props. Formisch defines all validation in the schema, next to the structure it validates. - **Validation timing**: Formik has two boolean switches, `validateOnChange` and `validateOnBlur`, both `true` by default, so validation runs on every keystroke from the start. Formisch uses the `validate` and `revalidate` options with event-based modes and by default stays quiet until the first submit. - **Error display**: Formik computes `errors` eagerly and expects you to gate their display with the `touched` object, which is what `ErrorMessage` does internally. In Formisch, errors appear on a field only once validation has run, so no gating is needed in the default configuration. - **Reactivity**: Formik stores all form state in React state, so every keystroke re-renders the entire `` subtree, which is why `` exists. Formisch is built on fine-grained signals, so each field only re-renders when its own state changes. - **Field binding**: Formik connects inputs by string name (``). Formisch connects fields through the headless [`Field`](/react/api/Field.md) component with a type-safe path array (`path={['user', 'email']}`). If your forms already use `validationSchema`, the structure of your Yup schemas translates almost one-to-one to Valibot. #### Side-by-side example The following login form has two validated fields, displays error messages, disables the submit button while submitting, and processes the values on submission. ##### Formik ```tsx import { ErrorMessage, Field, Form, Formik } from 'formik'; import * as Yup from 'yup'; const LoginSchema = Yup.object({ email: Yup.string() .required('Please enter your email.') .email('The email address is badly formatted.'), password: Yup.string() .required('Please enter your password.') .min(8, 'Your password must have 8 characters or more.'), }); export default function LoginPage() { return ( { // Process the validated form values console.log(values); }} > {({ isSubmitting }) => ( )} ); } ``` ##### Formisch ```tsx import { Field, Form, type SubmitHandler, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema }); const onSubmit: SubmitHandler = async (values) => { // Process the validated form values console.log(values); }; return (
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
{(field) => (
{field.errors &&
{field.errors[0]}
}
)}
); } ``` Notice how the Yup schema became a Valibot schema that now also provides the form's types, and how `initialValues` disappeared because required string fields start as an empty string automatically. The `onSubmit` handler moved from the `Formik` component to the [`Form`](/react/api/Form.md) component and receives the validated output of the schema. And instead of the `ErrorMessage` component, each field renders its `field.errors` directly. One timing difference: Formik validates on every keystroke from the start and hides the messages behind its `touched` gate, while Formisch by default validates on the first submit and then revalidates on every input. The [validation timing](#validation-timing) section below shows how to align the two. #### Migration steps ##### Install Formisch Add Formisch and Valibot alongside Formik. Both form libraries can run in parallel during the migration. ```bash npm install @formisch/react valibot ``` See the [installation](/react/guides/installation.md) guide for other package managers. ##### Move validation into a Valibot schema Translate your Yup schema, `validate` function, or field-level `validate` props into a single Valibot schema. Most Yup rules have a close counterpart: string `.required()` becomes `v.nonEmpty()`, string `.min()` becomes `v.minLength()`, `.email()` becomes `v.email()`, and `.matches()` becomes `v.regex()`. Other input types need their corresponding Valibot schema and actions. ```ts import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), }); ``` Cross-field rules that you built with `Yup.ref`, such as a password confirmation, become schema-level checks with `v.forward` and `v.partialCheck`. Define the fields in the same order they appear in your form, since Formisch focuses the first invalid field on submit based on the schema order. The [define your form](/react/guides/define-your-form.md) guide covers schema design in detail. ##### Replace the form setup Whether your forms use the `useFormik` hook, the `` component, or the `withFormik` higher-order component, they all become the same [`useForm`](/react/api/useForm.md) hook. There is no render-prop or HOC variant because you read state directly from the returned form store. ```tsx // Before import { useFormik } from 'formik'; const formik = useFormik({ initialValues: { email: '', password: '' }, validationSchema: LoginSchema, onSubmit: async (values) => { console.log(values); }, }); ``` ```tsx // After import { useForm } from '@formisch/react'; const loginForm = useForm({ schema: LoginSchema }); ``` `initialValues` is replaced by the optional `initialInput`: required string fields start as an empty string automatically, so you only pass it when you have real data, such as a profile loaded from the server. The `onSubmit` option moves to the `Form` component (see below), and the `validateOnChange` and `validateOnBlur` switches map to the `validate` and `revalidate` options. See the [create your form](/react/guides/create-your-form.md) guide for all configuration options. ##### Replace field bindings Replace each Formik `Field` with the Formisch [`Field`](/react/api/Field.md) component. The Formisch version is headless: it never renders an input itself, so the `as`, `component`, and children variants of Formik's `Field` all become the same pattern, a render function that spreads `field.props` onto your input and binds `field.input` as its value. Where you wired inputs manually with `getFieldProps('email')` or `handleChange`, `handleBlur`, and `values.email`, the spread replaces all of them at once. ```tsx // Before <> ``` ```tsx // After {(field) => (
{field.errors &&
{field.errors[0]}
}
)}
``` String names become type-safe path arrays: `name="user.email"` turns into `path={['user', 'email']}` and ``name={`todos.${index}.label`}`` turns into `path={['todos', index, 'label']}`. The `ErrorMessage` component disappears: `field.errors` is either `null` or a non-empty array of strings, so you render it right next to the input. Custom inputs built on Formik's `useField` map to the Formisch [`useField`](/react/api/useField.md) hook, which returns a single field store instead of a `[field, meta, helpers]` tuple: `meta.error` becomes `field.errors`, `meta.touched` becomes `field.isTouched`, and `helpers.setValue` becomes `field.onChange`. The [add form fields](/react/guides/add-form-fields.md) guide explains both in detail. ##### Update submission handling Replace the `
` element wired to `formik.handleSubmit` (or Formik's own `Form` component) with the Formisch [`Form`](/react/api/Form.md) component, and move the handler from the form config to its `onSubmit` prop. The handler only runs after validation succeeds and receives the validated values, typed as the schema's output. ```tsx // Before {/* fields */}
// After
{/* fields */}
``` `setSubmitting` disappears. Formik resets `isSubmitting` automatically only when your handler returns a promise and expects a manual `setSubmitting(false)` otherwise, while Formisch manages `loginForm.isSubmitting` in both cases. The same applies to the rest of Formik's submission bag: helpers like `resetForm` and `setFieldError` that Formik passes as the second argument are standalone methods in Formisch, such as [`reset`](/methods/api/reset.md) and [`setErrors`](/methods/api/setErrors.md), which you call with the form store from anywhere. See the [handle submission](/react/guides/handle-submission.md) guide for details. #### API mapping | Formik | Formisch | | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `useFormik` / `` / `withFormik` | [`useForm`](/react/api/useForm.md) with `schema` (types are inferred) | | `initialValues` | `initialInput` option (optional) | | `validationSchema` / `validate` | `schema` option | | `validate` prop of `Field` | Validation rules in the schema | | `validateOnChange` / `validateOnBlur` | `validate` / `revalidate` options (see notes) | | `
` | [`Form`](/react/api/Form.md) component with `of` and `onSubmit` props | | `` | [`Field`](/react/api/Field.md) component with `path={['email']}` | | `getFieldProps('email')` | Spread `field.props` and bind `value={field.input}` | | `` | `field.errors` rendered next to the input (see notes) | | `useField('email')` | [`useField`](/react/api/useField.md) hook with `path: ['email']` | | `values` | `field.input`, [`getInput`](/methods/api/getInput.md) | | `errors` | `field.errors` per field, [`getErrors`](/methods/api/getErrors.md), [`getDeepErrors`](/methods/api/getDeepErrors.md) | | `touched` | `field.isTouched` (see notes) | | `dirty` | `form.isDirty` (see notes) | | `isValid` | `form.isValid` (see notes) | | `isSubmitting` | `form.isSubmitting` | | `isValidating` | `form.isValidating` | | `submitCount` | No direct equivalent (see notes) | | `handleSubmit` / `submitForm` | `onSubmit` prop of [`Form`](/react/api/Form.md), [`submit`](/methods/api/submit.md) | | `handleReset` / `resetForm` | [`reset`](/methods/api/reset.md) | | `enableReinitialize` | [`reset`](/methods/api/reset.md) with `initialInput` (see notes) | | `setFieldValue` / `setValues` | [`setInput`](/methods/api/setInput.md) | | `setFieldError` / `setErrors` | [`setErrors`](/methods/api/setErrors.md) | | `setFieldTouched` / `setTouched` | No direct equivalent (see notes) | | `validateField` / `validateForm` | [`validate`](/methods/api/validate.md) (see notes) | | `` | [`FieldArray`](/react/api/FieldArray.md) component or [`useFieldArray`](/react/api/useFieldArray.md) hook | | `push` / `unshift` / `insert` | [`insert`](/methods/api/insert.md) | | `remove` / `pop` | [`remove`](/methods/api/remove.md) | | `swap` / `move` / `replace` | [`swap`](/methods/api/swap.md), [`move`](/methods/api/move.md), [`replace`](/methods/api/replace.md) | | `` | Not needed (see notes) | | `useFormikContext` / `connect` | Not needed (see notes) | | `status` / `setStatus` | No equivalent (see notes) | A few entries deserve extra context: - **`ErrorMessage` and the `touched` gate**: Formik validates eagerly and computes `errors` for every field, so their display must be gated behind `touched`, which `ErrorMessage` handles internally. Formisch populates `field.errors` only once validation has actually run for a field. With the default `validate: 'submit'` timing there is nothing to gate, and if you validate earlier, guard the display with field state like `isEdited`, as shown in the [validation](/react/guides/validation.md) guide. - **`touched`**: Formisch marks a field as touched when it receives focus or its input is set, while Formik marks it on blur. During ordinary keyboard interaction that means touched-based logic usually reacts on focus instead of waiting for blur. - **`dirty`**: Formik's `dirty` is comparison-based: it is `true` while `values` differs from `initialValues` and flips back off when the user reverts their changes. That matches `form.isDirty` exactly. Formisch's `form.isEdited` is the sticky variant that stays `true` once anything was edited, even after the value is changed back. - **`isValid`**: In Formisch, `form.isValid` reflects the result of the last validation run. With the default `validate: 'submit'` timing it stays `true` until the first submit, unlike Formik's `isValid`, which is recomputed on every change. If you rely on it before the first submit, for example to disable the submit button, set `validate: 'initial'`. - **`submitCount`**: Formisch tracks whether the form has been submitted as the boolean `form.isSubmitted` instead of a counter. If you used `submitCount > 0` to reveal errors after the first submit attempt, `form.isSubmitted` covers that. An actual attempt count requires your own state. - **`validateField`**: The [`validate`](/methods/api/validate.md) method always validates the entire form against the schema. The results are still distributed per field, so field-level triggering is not necessary. - **`setFieldTouched` / `setTouched`**: There is no imperative touched setter. Fields become touched automatically when they receive focus or their input is set, and the custom blur handlers these helpers are typically used in are replaced by spreading `field.props`. This also means Formisch's `setInput` marks the field as touched and edited, whereas Formik's `setFieldValue` does not mark it as touched. - **``**: `FastField` exists to cut down Formik's subtree re-renders. Formisch's signal-based store already re-renders each field only when its own state changes, so an opt-out component is not needed. - **`useFormikContext` / `connect`**: The Formisch form store is a plain object. Pass it down as a prop, as our [input components](/react/guides/input-components.md) do, or share it through your own React context if you prefer. - **`status` / `setStatus`**: Form-adjacent state like a submission error message is regular component state in Formisch. For errors that should live on the form itself, [`setErrors`](/methods/api/setErrors.md) sets root-level errors that appear in `form.errors`. #### Common patterns ##### Form state Formik hands you form state through the object returned by `useFormik` or through render props, and updating any part of it re-renders everything below the form. In Formisch, you read state directly from the form store. Reads are tracked through signals, so components re-render automatically and only when the state they read changes. ```tsx // Before const formik = useFormik({ initialValues, onSubmit }); ; // After const profileForm = useForm({ schema: ProfileSchema }); ; ``` The form store exposes `isSubmitting`, `isSubmitted`, `isValidating`, `isTouched`, `isEdited`, `isDirty`, `isValid`, and `errors`. To read field values in component logic, use the [`getInput`](/methods/api/getInput.md) method, which also stays reactive inside components. ##### Validation timing Formik's timing options are boolean switches: `validateOnChange` and `validateOnBlur` turn whole trigger types on or off, and `validateOnMount` validates once on mount. Formisch instead distinguishes between the first validation of a field and every following one: ```tsx // Closest match to Formik's default behavior const loginForm = useForm({ schema: LoginSchema, validate: 'input', }); ``` The `validate` option controls when a field is first validated (`'initial'`, `'touch'`, `'input'`, `'change'`, `'blur'`, or `'submit'`), and `revalidate` controls when it is checked again once it has an error or the form was submitted. With `validate: 'input'`, each field is validated from the first keystroke, like Formik's default. In practice, the behavior your users saw is closer to `validate: 'blur'` with `revalidate: 'input'`, because Formik's `touched` gate delays the first visible error until the field is left. If you disabled both switches to validate only on submit, use `validate: 'submit'` with `revalidate: 'submit'` for the same behavior. The Formisch defaults (`validate: 'submit'`, `revalidate: 'input'`) also stay quiet until the first submit, but afterwards they re-check fields on every keystroke instead of leaving stale errors until the next submit. Finally, `validateOnMount` maps to `validate: 'initial'`. The [validation](/react/guides/validation.md) guide covers all modes and how to show errors at the right time. ##### Field arrays Formik's `FieldArray` provides its mutation helpers through a render prop, you map over the corresponding value from `values`, and the docs key items by index: ```tsx // Before, inside the render prop {({ push, remove }) => (
{values.todos.map((_, index) => (
))}
)}
``` In Formisch you use the [`FieldArray`](/react/api/FieldArray.md) component and standalone methods. The `items` array contains stable unique IDs to use as keys, so React correctly tracks items when they are added, moved, or removed: ```tsx // After import { Field, FieldArray, insert, remove } from '@formisch/react'; {(fieldArray) => (
{fieldArray.items.map((item, index) => (
{(field) => }
))}
)}
; ``` The helpers map as follows: `push` becomes [`insert`](/methods/api/insert.md), which appends by default, `unshift` becomes `insert` with `at: 0`, and `insert(index, value)` becomes `insert` with the `at` option. `remove(index)` and `pop` become [`remove`](/methods/api/remove.md) with the `at` option, while `swap`, `move`, and `replace` map one-to-one. Unlike Formik's helpers, the Formisch methods are not bound to a render prop: they work anywhere you have access to the form store. Rules like a minimum or maximum number of items move into the schema, for example `v.pipe(v.array(…), v.maxLength(10))`. See the [field arrays](/react/guides/field-arrays.md) guide for the full picture. ##### Reset Formik's `resetForm()` restores `initialValues`, and `resetForm({ values })` replaces them. The Formisch [`reset`](/methods/api/reset.md) method covers both through its config object and additionally resets individual fields through the `path` option. ```tsx import { reset } from '@formisch/react'; // Reset the entire form to its initial input reset(profileForm); // Reset with new initial input, e.g. after refetching server data reset(profileForm, { initialInput: { name: 'Jane' } }); // Reset a single field reset(profileForm, { path: ['email'] }); ``` `reset` with `initialInput` also replaces `enableReinitialize`: instead of a flag that watches `initialValues` with deep equality, you call `reset` with the fresh data when it arrives, for example in an effect after a refetch. As in Formik, resetting updates the baseline for dirty tracking. Fields you plan to reset programmatically must be controlled, so bind `value` or `checked` as described in the [controlled fields](/react/guides/controlled-fields.md) guide. ##### Special inputs Formik switches its binding behavior based on the `type` you pass to `Field` or `useField`: `type="checkbox"` binds `checked`, and radio buttons compare against `value`. In Formisch, you spread `field.props` and bind the state attribute that matches the input type yourself: ```tsx {(field) => ( )} ``` The [special inputs](/react/guides/special-inputs.md) guide covers checkboxes, radio buttons, selects, and file inputs in detail. One caveat carried over from the DOM: event handlers read strings, so where you parsed `event.target.value` inside a `setFieldValue` call, fields with a `v.number()` or `v.date()` schema need to be controlled instead, as explained in the [controlled fields](/react/guides/controlled-fields.md) guide. #### Next steps You now have everything you need to migrate your forms one at a time. Start with the [define your form](/react/guides/define-your-form.md) and [create your form](/react/guides/create-your-form.md) guides to deepen the schema-first workflow, build reusable [input components](/react/guides/input-components.md) to replace your Formik field components, and explore the [form methods](/react/guides/form-methods.md) guide for everything that replaces Formik's imperative helpers. ## Integration guides (guides) ### shadcn/ui [shadcn/ui](https://ui.shadcn.com) is a collection of accessible components that you copy into your project and adapt to your needs. This guide targets shadcn CLI v4 components generated with Base UI v1 and works with every official visual style. No adapter package is needed: native controls receive `field.props`, while controlled components map Formisch's value and lifecycle APIs to the generated component. #### Installation Initialize shadcn/ui with Base UI and choose whichever visual style fits your project. Then add the components used below: ```bash npx shadcn@latest init --base base npm install @formisch/react valibot npx shadcn@latest add field input textarea checkbox select radio-group slider button ``` Skip the `init` command if shadcn/ui is already configured with Base UI. The generated `field` component provides the layout, label and error components used throughout this guide. #### Wiring patterns Choose the wiring from the component's public API: - If it forwards props and a ref to a native form element, spread `field.props` and pass `field.input` as its value. - If it exposes a custom callback such as `onCheckedChange` or `onValueChange`, control it with `field.input` and `field.onChange`, then forward the remaining lifecycle props separately. ##### Spreading field.props shadcn's `Input` and `Textarea` render native elements, so their wiring is the same as a plain HTML input: ```tsx {(field) => } ``` ##### Controlled components A controlled component needs more than its value callback. Preserve Formisch's lifecycle behavior by passing its field name and hidden-input ref, and by forwarding focus, blur and autofocus behavior to the visible control: ```tsx {(field) => ( )} ``` `inputRef` registers Base UI's hidden native input so Formisch can focus the field. Formisch's focus and blur handlers are parameterless because they only update field lifecycle state, so you can pass them directly even when the component supplies an event argument. These examples wire fields directly so you can see the complete integration. Once a pattern repeats, wrap the label, control, lifecycle props and errors in your own input component. This keeps forms concise and defines the wiring in one place. The [input components guide](/react/guides/input-components.md) shows how. #### Displaying errors Formisch exposes errors as `[string, ...string[]] | null`. shadcn's `FieldError` expects objects with a `message` property, so map the strings before passing them. Give the error a stable ID and reference it from the input when an error is present: ```tsx {(field) => ( Email ({ message }))} /> )} ``` Use page-unique IDs for labels and errors instead of assuming that a field name is unique in the DOM. By default, Formisch validates on submit and revalidates on input. The [validation guide](/react/guides/validation.md) explains how to change that timing. #### Login form example This complete example combines native inputs, a controlled checkbox and accessible errors: ```tsx import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { FieldError, FieldLabel, Field as UIField, } from '@/components/ui/field'; import { Input } from '@/components/ui/input'; import { Field, Form, type SubmitHandler, useForm } from '@formisch/react'; import * as v from 'valibot'; const LoginSchema = v.object({ email: v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email address is badly formatted.') ), password: v.pipe( v.string(), v.nonEmpty('Please enter your password.'), v.minLength(8, 'Your password must have 8 characters or more.') ), rememberMe: v.optional(v.boolean(), false), }); export default function LoginPage() { const loginForm = useForm({ schema: LoginSchema, initialInput: { email: '', password: '', rememberMe: false, }, }); const handleSubmit: SubmitHandler = (output) => { console.log(output); }; return ( {(field) => ( Email ({ message }))} /> )} {(field) => ( Password ({ message }))} /> )} {(field) => ( Remember me )} ); } ``` The initial input keeps every control defined from its first render. The native inputs use the `field.props` spread, while the checkbox maps Base UI's value and lifecycle APIs explicitly. #### Component reference The following snippets assume a form store named `form` and initialized values that match the schema. ##### Text input `Input` forwards to a native ``, so spread `field.props` directly: ```tsx {(field) => ( Email ({ message }))} /> )} ``` `Textarea` works the same way because it also renders a native element. ##### Checkbox For a boolean field, control `checked` and register Base UI's hidden input: ```tsx {(field) => ( Newsletter )} ``` ##### Select Base UI represents no selection as `null`, while an optional Formisch value is `undefined`. Convert between them and put the lifecycle handlers on the visible trigger: ```tsx const frameworks = [ { label: 'Angular', value: 'angular' }, { label: 'React', value: 'react' }, { label: 'Solid', value: 'solid' }, { label: 'Vue', value: 'vue' }, ]; ``` ```tsx {(field) => ( Framework ({ message }))} /> )} ``` The `items` prop lets `SelectValue` display the selected item's label. ##### Radio group Connect the legend to the `radiogroup` explicitly. A surrounding `fieldset` alone does not give Base UI's nested group an accessible name: ```tsx {(field) => (
Plan { if (!event.currentTarget.contains(event.relatedTarget)) { field.props.onFocus(); } }} onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) { field.props.onBlur(); } }} onValueChange={field.onChange} > Hobby Pro ({ message }))} />
)}
``` The focus guards treat the composite group as one field, so arrow-key navigation between items does not trigger blur validation. Place `autoFocus` on the first radio item so Formisch can move focus into the group after validation. ##### Slider The generated `Slider` does not expose Base UI's thumb `inputRef`. Since shadcn adds the component source to your project, update `components/ui/slider.tsx` once: extend `SliderPrimitive.Root.Props` with `inputRef?: SliderPrimitive.Thumb.Props['inputRef']`, destructure it in `Slider`, and pass `inputRef={index === 0 ? inputRef : undefined}` to the generated `SliderPrimitive.Thumb`. The Formisch wiring then stays simple. Pass a one-element array for one thumb because a scalar value makes the generated wrapper fall back to `[min, max]` and render two thumbs. Also give the visible label an ID because a slider cannot be associated with `htmlFor`: ```tsx {(field) => ( Volume field.onChange(Array.isArray(value) ? (value[0] ?? 50) : value) } onFocus={field.props.onFocus} onBlur={field.props.onBlur} min={0} max={100} /> ({ message }))} /> )} ``` The ref registers the thumb's nested range input, so Formisch's `focus()` method and submit-time error focusing work without querying the DOM. Base UI's slider thumb does not expose an input-level `autoFocus` prop, but registering the input preserves Formisch's programmatic focusing. #### Library-specific notes shadcn/ui also publishes a [Formisch forms guide](https://ui.shadcn.com/docs/forms/formisch) with complete form examples. This guide focuses on the details behind each field binding so you can adapt them to your own components. The generated APIs depend on the primitive selected during `shadcn init`. Radix UI and React Aria components use different refs and callback signatures, so verify their generated source instead of copying the Base UI-specific props from this guide. #### Next steps Read the [input components](/react/guides/input-components.md) guide to package repeated wiring into reusable controls, the [controlled fields](/react/guides/controlled-fields.md) guide for the underlying pattern, and the [validation](/react/guides/validation.md) guide for validation timing. ### Ark UI [Ark UI](https://ark-ui.com) is a headless component library built on state machines, available for React among other frameworks. This guide targets Ark UI v5 for React. No adapter package is needed: each component exposes the native element as one of its parts, so you spread `field.props` onto that part and let the component root handle the value. #### Installation Install Formisch, Valibot and Ark UI: ```bash npm install @formisch/react valibot @ark-ui/react ``` Ark UI ships unstyled, so every example below leaves styling to you. #### Wiring patterns Choose the wiring from the part you are rendering: - If the part is a native ``, `