---
title: 'Form state'
description: 'What a rendered form holds, how to read it from React hooks and from Radiant, and how it validates, submits and resets.'
order: 7
---

# Form state

Every rendered form has one **form state**: the nested values, the errors and warnings of each field, the touched, dirty and pending marks, the row ids of field arrays and what the browser reports about each control. React and Radiant both read it, so a form validates, resets and submits the same way in either. Nothing else keeps form state: there is no form library underneath, so there is nothing to wire between a form and the code around it beyond values in and values out.

You do not create it: `FormRenderer` does. You read and write it with the React hooks or, in Radiant, with `FormController`. A renderer of your own binds to the [state container](/docs/renderer-authors/state-container) directly.

## What it holds

The form's state is one immutable snapshot. It is the same object until something changes, and a branch that did not change keeps its reference, so it is safe to compare by identity. A renderer reads it for you; its members are these:

| Member          | Holds                                                                                                            |
| --------------- | ---------------------------------------------------------------------------------------------------------------- |
| `values`        | The nested value tree.                                                                                           |
| `errors`        | The error of each path, flat by dotted path (`contacts.0.email`). The form itself is `FORM_ROOT` (`'__root__'`). |
| `warnings`      | Advice from rules declared `severity: 'warning'`, shaped and timed like errors. A warning never blocks.          |
| `touched`       | The paths the user has blurred. A mark on a container covers the fields below it.                                |
| `dirty`         | The paths whose value differs from the defaults.                                                                 |
| `validating`    | The paths a check is still running for.                                                                          |
| `rowIds`        | The ids of each array's rows, by array path. A field array renders by these ids.                                 |
| `isValid`       | Whether no error is recorded for a path that takes part. See [Validity](#validity).                              |
| `generation`    | How many times the form was reset.                                                                               |
| `participation` | The ids of the skipped steps and the state of each field a constraint or authoring hides, disables or requires.  |

An error is never inherited: `errors['contacts']` is the array's own error and `errors['contacts.0.email']` the row's, and both can be present. An error is an issue with every issue of its path in `all`, ordered as what the server said, then each rule the value fails in authored order, then what the browser reported. Its `type`, `ruleId` and `params` say what is wrong; [Issue text](/docs/forms/issue-text) says how to word it.

In Radiant, `FormController.select` takes selectors, which are pure functions of the snapshot and memoized per snapshot and path:

| Selector                              | Returns                                                                                                                                               |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `selectFieldState(snapshot, path)`    | `error` (exactly that path's, never one inherited), `warning`, `invalid`, `isTouched`, `isDirty`, `isValidating`, `hidden`, `disabled` and `required` |
| `selectValue(snapshot, path)`         | The value at the path                                                                                                                                 |
| `toFieldArrayValue(rowIds, commands)` | `fields` with stable ids and the array operations, as a widget takes them                                                                             |

A field state is the same object in every snapshot while it is unchanged.

## Read it in React

The hooks come from `@schema-engine/forms-react/hooks` and have to run inside the form, so render the component as a child of `FormRenderer`:

| Hook                                           | Reads                                                                                                                                                 |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useFormContext()`                             | `getValues`, `setValue`, `validate`, `reset`, `setFocus`, `formatIssue`, `clearSubmission` and a lazy `formState` (`errors`, `isValid`, `submission`) |
| `useWatch(path)`                               | The value at a path, a list of paths, or every value when called with none                                                                            |
| `useFieldArray(path)`                          | `fields` with stable ids, and `append`, `prepend`, `insert`, `swap`, `move`, `update`, `replace` and `remove`                                         |
| `useFormField(config)` or `useFormField(path)` | One field's state and props, for a [widget](/docs/forms-react/widgets)                                                                                |
| `useFormWizard()`                              | The wizard: see [Wizard](/docs/forms/wizard)                                                                                                          |

A component renders again only for what it reads. Reading `formState.submission` renders it when the submission changes and not while the user types, and `isValid` reports the recorded errors and validates nothing. This status line reads one value and the submission, and starts over:

```tsx title="react-form-status.react.tsx"
import { isSubmissionBusy } from '@schema-engine/forms';
import { FormRenderer } from '@schema-engine/forms-react';
import { useFormContext, useWatch } from '@schema-engine/forms-react/hooks';
import { contactForm, engine } from './react-quick-start.react';

/** What the form knows about the visitor's progress: the email typed so far, the submission and a way to start over. */
function FormStatus() {
	const { formState, reset } = useFormContext();
	const email = useWatch('email');
	const { status, submitCount } = formState.submission;
	return (
		<footer>
			<output>
				{typeof email === 'string' && email !== '' ? `Writing to ${email}. ` : ''}
				{isSubmissionBusy(status) ? 'Sending' : `Submissions: ${submitCount}`}
			</output>
			<button type="button" onClick={() => reset()}>
				Start over
			</button>
		</footer>
	);
}

/** The contact form of the quick start with a status line under it, rendered as a child of the form. */
export function ContactWithStatus({ onSubmit }: { onSubmit: () => void }) {
	return (
		<FormRenderer engine={engine} config={contactForm} onSubmit={onSubmit}>
			<FormStatus />
		</FormRenderer>
	);
}
```

It renders the contact form of the [React quick start](/docs/forms-react/getting-started). [Hooks](/docs/forms-react/hooks) lists every hook.

## Read it in Radiant

`new FormController(host)` for an element inside the form gives its `container` (the commands and reads: `getValue`, `setValue`, `validate`, `reset`, `fieldArray`), `select(selector)`, a signal over a selector of the snapshot, and `formatIssue(issue, { path })`. It also gives `submission`, a signal over the submission (`undefined` while the form has no runtime), `clearSubmission()`, which hides the outcome of the last submission, and `wizard`, a signal over the [wizard](/docs/forms/wizard#in-radiant). [Form controls](/docs/forms-radiant/form-controls#read-the-form-from-your-own-element) has an element that follows the rows of an array with it. Values are nested and paths are dotted (`contacts.0.email`).

## Write it

| From                                                  | Does                                                                                                                              |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `setValue(path, value)`                               | Replaces the whole branch at the path. It is a change: it validates when the mode says so and drops what described the old value. |
| `useFieldArray(path)` or `container.fieldArray(path)` | Adds, moves and removes rows. Each command is one update, and a row's state moves with it.                                        |
| `reset(values?)`                                      | Restores the defaults, or replaces them with `values` first, and clears errors, marks and the submission: a fresh form.           |

A path with a segment that starts with `__`, or is `constructor` or `prototype`, is rejected, and so is a write to a row the array does not have: make rows with the array's commands.

## Validity

Three reads answer "is the form valid", and they differ on purpose. `validate` is `useFormContext().validate` in React and `container.validate` in Radiant, and `checkValidity` is `container.checkValidity` and `context.form.checkValidity()` in an action.

| Read                     | Answers                                                                                                                                                                                                                                                                                                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `snapshot.isValid`       | Whether no error is recorded right now for a path that takes part. It validates nothing, so a pristine form with an empty required field is `true`.                                                                                                                                                                                             |
| `await validate(paths?)` | Validates the paths (the whole form when omitted), records and shows the errors, and resolves `{ outcome }`: `'passed'` only when no error remains and the check was still current when it finished, otherwise `'invalid'` or `'overtaken'`. It rejects with a `FormValidationFailure` (from `@schema-engine/forms`) when a rule could not run. |
| `await checkValidity()`  | Validates the values current at the call and resolves whether the form passes. It records and shows nothing, and its answer may be out of date when it resolves.                                                                                                                                                                                |

After `'short'` is typed under a `minLength` rule of 8, the recorded state is still valid, `checkValidity()` is `false` and leaves it so, and `validate()` resolves `{ outcome: 'invalid' }` and records the `minLength` error.

Do not disable a submit button with `isValid`. A server error makes it `false`, and only the next attempt clears that, so the user could not retry. Let the user submit and show the errors.

Actions see the same three. In an action, `context.isValid` is `isValid`, `context.form.checkValidity()` is `checkValidity()` and `context.form.validate()` is `validate()`, so it resolves `{ outcome }` too. See [Actions in forms](/docs/forms/actions#stop-on-failure).

A check is **fresh** only while its scope is current. If an edit, a row move or a reset outruns it, `validate()` runs once more over the same rows, and if it is overtaken again it resolves `{ outcome: 'overtaken' }` and writes nothing stale. `'overtaken'` is no verdict: ask again, and do not treat it as `'invalid'`.

## Submit

A submit validates the whole form, then runs in this order:

1. An invalid form shows its errors and focuses the first control. A check that an edit outran stops without showing anything. Neither is a submission, so the status goes back to `idle`.
2. The values that passed are parsed with the [submission schema](#submitted-values). A mismatch stops the submission with a `valueMismatch` failure and is logged.
3. The status becomes `submitting`, and `form_submit_start` runs.
4. The submit actions run (`form_submit`). An action that fails and stops the sequence skips `onSubmit`.
5. `onSubmit(values, { setServerErrors, fetch })` runs with the values that passed. A rejection is a failed submission.
6. `form_submit_success` runs, or `form_submit_error` after a failure, then `form_submit_complete`.

A second submit while one runs is `busy`. `useFormContext().formState.submission` reports `{ status, failures, submitCount }`. `status` is `idle`, `validating` (while the check runs), `submitting` (once it passed, while the actions and `onSubmit` run), `success` or `error`; `isSubmissionBusy(status)`, exported by `@schema-engine/forms`, is true for `validating` and `submitting`. `failures` are issues of the form itself (`actionFailed`, `callbackFailed`, `triggerFailed`, `validationFailed`, `valueMismatch`), and `submitCount` counts submissions that passed or failed validation, not a Next and not a check an edit outran. A reset returns it to idle with a count of 0, unless the submission's values were already captured: it is then committed and publishes its outcome (`success` or `error`, with a count of 1) after the reset.

Send the values with the `fetch` of `onSubmit`'s second argument, which applies the [CSRF policy](/docs/forms/csrf), and show the server's answer with `setServerErrors`. See [Server errors](/docs/forms/server-errors).

## Submitted values

The type of the values a form submits comes from the form config, and the form checks that it is true. The example below is a React form's: it uses the engine of [Writing a widget](/docs/forms-react/widgets), and a Radiant form gets the same types.

**Each input declares the value its control writes.** `defineInput({ $type, schema, metadata, render, value })` takes `value`, a function of the configured element that returns any Standard Schema: a select's `options` become an enum (a list of it with `multiple`), a rating's `max` a bound. A container (a schema that declares `elements`, with an optional `containerKind`) declares none, since its value is its children's; a static element has none. Every input of the Radiant and registry packages declares its own.

**The engine composes them.** `engine.submissionSchema(config)` follows the rules the container submits by: dotted names nest (`address.street` is `{ address: { street } }`), a named container is an object of its children, a container of kind `array` is a list of rows, a one-child row is a list of values (unless `initialValues` or the child's `defaultValue` is a record, or the child is a container of its own that is not an array, such as a group, which makes the rows objects of the array's children), and the config's `payload` keys are added as they are. A key in `defaultValues` that no field declares is not submitted: `payload` is the one way to send extra data. The schema has `~standard.jsonSchema`, whose `input()` and `output()` throw when a value schema has no JSON Schema (a Zod schema exports with unrepresentable parts left open).

**A key is absent or present, by one rule.** A hidden or disabled field, a field of a skipped step and a field never written are missing keys. A key is required in the schema and the type only when the field has a `required` rule and neither it, a container around it nor its step has `constraints` or `disabled`; any of those can leave it out. An optional leaf field's empty value (`''` or `null`) is submitted as it is, so a PATCH can tell "cleared" from "untouched", and its type allows it. A list or a group has no such value: its empty value is its empty list or object.

**The form checks every submission.** After validation passes and before the submit actions, the form parses the values with that schema. A mismatch is a broken element contract, not a user error: the submission fails with a form-level `valueMismatch` issue whose `params.path` names the field (`contacts.1.email`), the error is logged, and `onSubmit` never receives the values. `defaultValues` are checked once against a partial of the schema when the form is created: a default that does not match its field is dropped whole, so the field starts as if it had none and its own rules (a required one) ask the user for it (a list is one field, so one bad row drops the default of the list, and a leaf inside a group is its own field), and a warning names the paths. The form still renders.

**Two ways to type it, one rule.**

- A TypeScript config: `engine.defineForm` with a literal config returns the normalized config carrying the inferred type, and a renderer types `onSubmit`, `onAction` and `defaultValues` from it, with no annotation. A config that is not a literal gives `FormValues`.
- A JSON config: `engine.validateForm(json, { values: Profile })` binds the application's schema. The form parses with it after the derived one, and the type is its output. Without `values`, `onSubmit` receives `FormValues`, still checked at runtime.

```tsx title="react-typed-values.react.tsx"
import * as z from 'zod/mini';
import { FormRenderer } from '@schema-engine/forms-react';
import { engine } from './react-widgets.react';

const profile = engine.defineForm({
	id: 'profile',
	steps: [
		{
			id: 'main',
			title: 'Profile',
			elements: [
				{ $type: 'text', name: 'name', rules: [{ $type: 'required' }] },
				{ $type: 'rating', name: 'stars' },
			],
		},
	],
});

/**
 * A literal config types `values` as `{ readonly name: string; readonly stars?: number | '' | null }`, with no
 * annotation.
 */
export function TypedProfile({ save }: { save: (name: string, stars: number | undefined) => Promise<void> }) {
	return (
		<FormRenderer
			engine={engine}
			config={profile}
			onSubmit={async (values) => save(values.name, typeof values.stars === 'number' ? values.stars : undefined)}
		/>
	);
}

const Profile = z.object({ name: z.string(), stars: z.optional(z.number()) });

/** A config that arrives as JSON binds the application's schema: `onSubmit` receives its output. */
export function LoadedProfile({
	json,
	save,
}: {
	json: unknown;
	save: (profile: z.output<typeof Profile>) => Promise<void>;
}) {
	return <FormRenderer engine={engine} config={engine.validateForm(json, { values: Profile })} onSubmit={save} />;
}
```

`onChange`, `useWatch` and live reads stay `FormValues`: live values hold excluded and unfinished data. `defaultValues` take `DefaultValuesOf` (exported by `@schema-engine/forms`): the values type with every key optional at every depth and an empty value allowed in place of any leaf field. The rows of a list are as the values type has them: an optional scalar row may be empty, and the rows of a field whose declared value is a list (a checkbox group) may not.

The type of a choice field (select, combobox, radio, checkbox group) is the union its declaration returns, such as `string | number | Array<string | number>` for a select, not the literal values of its `options`: a registration declares one value type for every configuration, and a function of the config cannot be read back at the type level. The runtime check is exact; narrow it in the application, as the example above does for `stars`.

## Reset

`reset` of `useFormContext`, an action's `form.reset`, a native reset button and `FormController.container.reset()` do the same: the values return to the defaults, the errors, marks and native facts are cleared, every row gets a new id, the submission returns to idle and a wizard returns to its first step, with no step trigger fired. A command whose values were not yet captured is cancelled. A submission whose values were already captured is committed: its lifecycle runs to its end and its outcome is published after the reset.

## Native validity

Both renderers read what the browser says about a control, such as a number input that holds `1e` or an email that is not one, and show it as an issue with `source: 'native'` beside the rules' own. When both apply, the rule's error is the one shown. Both render the form with `novalidate`, so the browser never shows its own bubbles or blocks a submit: the form decides validity. A Radiant form with an `action` or `method` and no `onSubmit` posts natively once the submission passed, with the [CSRF field](/docs/forms/csrf) when the policy allows it, and a React form submits through `onSubmit` only. How a renderer reports the facts is in [Native validity](/docs/renderer-authors/native-validity).

## Where to go next

- [Wizard](/docs/forms/wizard): read and move the steps of a form.
- [Issue text](/docs/forms/issue-text): word each error and warning in your language.
- [Other React state](/docs/forms-react/other-react-state): mount a form in a screen that has state of its own.
- [State container](/docs/renderer-authors/state-container) and [Write a renderer](/docs/renderer-authors/write-a-renderer): the contract a renderer binds to, for a framework without one.
