Touched and Dirty State
You'll learn: How to track which form fields users have interacted with so validation errors appear at the right moment, not too early or too late.
The Problem: When to Show Validation Errors
Imagine filling out a registration form. If every field showed a red "This is required!" error before you even clicked in it, that would be hostile and confusing. But if errors never appeared until you clicked submit, you'd waste time filling out invalid data.
The solution? Track two separate pieces of metadata for each field:
Touched State
A field becomes touched when the user has focused on it (clicked or tabbed into it), even if they didn't type anything. Think of it like "user acknowledged this field exists."
const [touched, setTouched] = useState({
email: false,
password: false
});
// Mark as touched on blur (when user leaves the field)
onBlur={() => setTouched(prev => ({ ...prev, email: true }))}
Use touched to control when validation errors appear: only show them for fields the user has visited.
Dirty State
A field becomes dirty when its current value differs from its initial value. Think "has the user changed anything here?"
const initialValues = { email: '', password: '' };
const [values, setValues] = useState(initialValues);
// A field is dirty if it differs from initial
const dirty = {
email: values.email !== initialValues.email,
password: values.password !== initialValues.password
};
Use dirty state to enable/disable the submit button: "has the user actually made changes worth saving?"
Why Both Matter
Touched controls error visibility (don't show errors for untouched fields), while dirty controls submit button state (don't enable submit if nothing changed). They answer different questions about user interaction.
Key Takeaway: Touched tracks "user has been here" to control error display timing; dirty tracks "value has changed" to enable smart submit behavior—together they create a polished form experience.