The "Controlled" Pattern
In a standard HTML form, the DOM itself handles the state of inputs. In React, we invert this control. By linking the value of an input to a React state, we ensure that React is the only source of truth.
Why Controlled?
- Instant validation feedback.
- Easy to disable/enable buttons based on state.
- Perfect for multi-step forms.
- Simplified data formatting on the fly.
Validation Snippet
if (email.length < 5) {
setError("Email too short");
}Preventing Default Behavior
Browsers naturally want to refresh the page when a form is submitted. In a Single Page Application (SPA), this is catastrophic. We intercept the event with e.preventDefault() to handle data via Fetch API or Axios without losing our app context.