Sub topic 3
Tracking form state
This chapter assumes you know basic HTML form elements, can read TypeScript, and understand that a browser submits a form as name/value pairs. It covers what a form needs to remember, how to store it, and the mistakes that appear once a form grows past a few fields.
What a form has to remember
A form is more than the text in its inputs. To show the right thing at the right time, you track four kinds of information per field:
- Value: what the user has entered or selected right now.
- Touched: whether the user has visited the field and left it (blurred it).
- Dirty: whether the value differs from the initial value.
- Error: the current validation message for the field, if any.
Each answers a different question. Value answers "what do we submit?" Touched answers "has the user had a fair chance to finish this field?" Dirty answers "has anything changed?" Error answers "what should we tell the user?"
The next chapter covers when to run validation. This chapter covers the state those rules read from and write to.
| Property | Set to true when | Typical use |
|---|---|---|
| Value | Always present | Submitting, validating, rendering the input |
| Touched | The field loses focus for the first time | Deciding whether to show an error yet |
| Dirty | The value differs from the initial value | Warning about unsaved changes, enabling "Save" |
| Error | A rule fails | Showing a message, blocking navigation |
Touched is not dirty
These two flags are easy to confuse, and they fail in different ways.
A user can tab through a required field without typing. The field is touched but not dirty. If you show errors only for dirty fields, that user never sees "Enter your full name" and later fails on submit with no warning.
A user can also type into a field and never leave it, for example by clicking "Next" directly. The field is dirty but not touched. If you show errors only for touched fields, the error stays hidden even though the user attempted to continue.
The fix is to mark every field in the current step as touched when the user attempts to move forward or submit. After that attempt, all errors become visible.
Where state lives
You have two main choices for where values live.
Uncontrolled inputs keep their value in the DOM. You read values when you need them, usually on submit, with FormData. This is simple and fast, and it works well for short forms. It gets awkward when other fields depend on a value, or when the form is split into steps and earlier inputs are removed from the DOM.
Controlled inputs keep values in your own state, and the input displays whatever that state says. Conditional logic, step changes, and drafts all become straightforward because the data exists independently of what is on screen.
For complex and multi-step forms, prefer a single state object owned above the individual fields. If step 1's inputs are unmounted when the user reaches step 2, their values must survive. A value that lives only in a DOM node will not.
A single state shape
Keep the four kinds of information in separate maps keyed by field name, plus the initial values for comparison:
type Values = Record<string, string>;
type FormState = {
initial: Values;
values: Values;
touched: Record<string, boolean>;
errors: Record<string, string>;
};
function createFormState(initial: Values): FormState {
return { initial, values: { ...initial }, touched: {}, errors: {} };
}
function isDirty(state: FormState, name: string): boolean {
return (state.values[name] ?? "") !== (state.initial[name] ?? "");
}
function isFormDirty(state: FormState): boolean {
const names = new Set([
...Object.keys(state.initial),
...Object.keys(state.values),
]);
return [...names].some((name) => isDirty(state, name));
}Dirty is derived here, not stored. Storing it as a separate flag invites bugs: if the user types "a" and then deletes it, a stored flag still says dirty, while the derived version correctly says the form is back to its initial state.
Errors are the other piece to consider. You can derive them from values on every render, or store them after validation runs. Deriving avoids stale messages. Storing lets you hold server-side errors, which your client rules cannot recompute. A common compromise is to derive client errors and keep server errors in a separate map, merging them for display.
Updating state with a reducer
A reducer is a pure function that takes the current state and an action and returns the next state. It keeps every state change in one place, which makes the behavior easy to test without a browser.
type Values = Record<string, string>;
type FormState = {
initial: Values;
values: Values;
touched: Record<string, boolean>;
errors: Record<string, string>;
};
type Action =
| { type: "change"; name: string; value: string }
| { type: "blur"; name: string }
| { type: "touchAll"; names: string[] }
| { type: "setErrors"; errors: Record<string, string> }
| { type: "reset"; values: Values };
function formReducer(state: FormState, action: Action): FormState {
switch (action.type) {
case "change":
return {
...state,
values: { ...state.values, [action.name]: action.value },
};
case "blur":
return {
...state,
touched: { ...state.touched, [action.name]: true },
};
case "touchAll": {
const touched = { ...state.touched };
for (const name of action.names) touched[name] = true;
return { ...state, touched };
}
case "setErrors":
return { ...state, errors: action.errors };
case "reset":
return {
initial: action.values,
values: { ...action.values },
touched: {},
errors: {},
};
}
}Three details matter here:
changedoes not set touched. Typing is not the same as leaving the field.touchAlltakes a list of names, so a multi-step form can touch only the fields on the current step.resetreplaces the initial values too. After a successful save, the saved values become the new baseline, and the form is no longer dirty.
Deciding what to show
Stored state is not the same as displayed state. The display rule is a small function that combines touched, submit attempts, and the error:
function visibleError(
errors: Record<string, string>,
touched: Record<string, boolean>,
name: string,
): string | undefined {
return touched[name] ? errors[name] : undefined;
}With touchAll run on a failed "Next" click, this shows nothing while the user is still working on a field, and shows every problem once they try to proceed.
The flow of state
The diagram shows how user events move through the state and into the interface.
Common errors
Treating an empty string and a missing key as different. A field the user never touched has no key in values, while a field the user cleared has "". Comparing undefined to "" makes a pristine form look dirty. The ?? "" in isDirty above handles this. Pick one convention and apply it everywhere.
Resetting state when a step unmounts. Some form libraries and component patterns discard a field's state when its input leaves the screen. In a multi-step flow this loses data the moment the user moves forward. Keep values in state owned by the whole flow, not by a step component.
Storing derived data. Dirty flags, "form is valid", and "number of errors" can all be computed from the core state. Each stored copy is another value that can disagree with the source.
Mutating state. Writing state.values[name] = value changes the object in place. Frameworks that compare by reference will not notice, and the screen will not update. Always return new objects, as the reducer does.
Validating on every keystroke and showing the result immediately. Users see "Enter a valid email" after typing a single character. State should support holding errors back until the field is touched, which is why touched exists.
Losing the user's input on a server error. A failed submit must not call reset. Keep values as they are and put the server's message into the error state.
Edge cases
- Checkboxes and multi-selects do not fit a
stringvalue. Usebooleanorstring[]for those fields, and adjust the dirty comparison, because["a"] !== ["a"]by reference. Compare by content, or serialize the value first. - Fields that disappear (conditional fields) keep their values in state unless you remove them. The conditional fields chapter shows how to exclude them from validation and submission.
- Browser autofill can set a value without firing the events you expect in some browsers. Read values from the input's
changeorinputevent, and test autofill by hand. - Number inputs return strings from the DOM. Keep them as strings in form state and convert at submission, so a half-typed value like
"1."is not discarded.
Exercise
A user opens step 2 of a form, types "abc" in the email field, and immediately clicks "Next" without leaving the field. The email rule fails. Which action should the Next handler dispatch so the error appears, and why is a blur-only approach not enough?
Show answer
Dispatch touchAll with the names of the fields on the current step (and then run validation). The user never blurred the email field, because clicking a button can happen before the blur is processed in your logic or the user may submit with the keyboard, so touched is still false and visibleError would hide the message. Marking every field on the step as touched when the user tries to proceed makes all current errors visible.
Exercise
A form starts with name "Ada". The user changes it to "Adam", then deletes the "m". Using the isDirty function from this chapter, is the field dirty? What would a stored dirty flag set on change report?
Show answer
The derived isDirty returns false, because "Ada" equals the initial value again. A stored flag set to true on the first change would still report dirty, so a "You have unsaved changes" warning would appear for a form that matches its saved state.