Sub topic 3
Tracking Form State
This chapter assumes basic HTML form elements, JavaScript or TypeScript, and how browsers submit form data. The goal is to track more than the current text in each field. A usable form also needs to know which fields the user has visited, whether values changed, and which messages should be shown.
The working model
Form state is the data that describes the form at a particular moment. Keep the main parts separate:
| State part | Meaning | Example |
|---|---|---|
| `values` | The current value of each field | `{ email: "[email protected]" }` |
| `touched` | The user has visited or left the field | `{ email: true }` |
| `dirty` | The value differs from its starting value | `{ email: true }` |
| `errors` | Messages for values that fail a rule | `{ email: "Enter a valid email." }` |
These parts answer different questions. A field can be touched but valid. It can be dirty but not touched if a script changed it. An error can exist before the user sees the field, so the interface should decide when to reveal it.
A useful state shape is:
type FormState = {
values: Record<string, string>;
touched: Record<string, boolean>;
dirty: Record<string, boolean>;
errors: Record<string, string>;
submitted: boolean;
};
const initialValues = {
email: "",
fullName: "",
};
const initialState: FormState = {
values: initialValues,
touched: {},
dirty: {},
errors: {},
submitted: false,
};Store field values in one object when fields share the same form. This makes serialization, draft saving, and final submission straightforward. Use stable field names as keys. Do not use a field's visual position as its identity.
State transitions
State changes should follow user actions. Common actions include:
change: update a value and mark the field dirty when it differs from its initial value.blur: mark the field touched.validate: add or remove an error.submit: mark the form submitted and validate the required fields.reset: restore the initial state.
A reducer is a function that receives the old state and an action, then returns new state. This makes transitions explicit and testable.
type Action =
| { type: "change"; name: string; value: string }
| { type: "blur"; name: string }
| { type: "setError"; name: string; message?: string }
| { type: "submit" };
function reducer(state: FormState, action: Action): FormState {
switch (action.type) {
case "change": {
const { name, value } = action;
return {
...state,
values: { ...state.values, [name]: value },
dirty: {
...state.dirty,
[name]: value !== initialValues[name as keyof typeof initialValues],
},
};
}
case "blur":
return {
...state,
touched: { ...state.touched, [action.name]: true },
};
case "setError": {
const errors = { ...state.errors };
if (action.message) errors[action.name] = action.message;
else delete errors[action.name];
return { ...state, errors };
}
case "submit":
return { ...state, submitted: true };
}
}Use immutable updates, which create new objects instead of changing existing ones. This helps UI frameworks detect changes and makes tests predictable.
Showing state to the user
A common display rule is to show an error after a field is touched or after submission:
function shouldShowError(
state: FormState,
name: string,
): boolean {
return Boolean(state.errors[name]) &&
(Boolean(state.touched[name]) || state.submitted);
}Do not use dirty alone to decide whether to show an error. A user may edit a field back to its original value, making it clean while the field still needs attention.
Common errors
Do not infer touched from whether a value is nonempty. A user may focus and leave a field empty. Do not clear all errors whenever any field changes. Clear or recalculate the affected error. Finally, keep server errors in the same error model or in a clearly separate field-level model, so the interface can associate each message with the correct control.
Exercise
Why should touched, dirty, and errors be stored separately?
Show answer
They describe different facts: whether the user visited a field, whether its value changed, and whether its value fails validation. Combining them causes incorrect error timing and confusing UI behavior.