The 'Single Source of Truth' Pattern
In a controlled component, the form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. In a controlled component, the input's current value is always driven by the React state, making the state the 'single source of truth'.
How Controlled Components Work
Every state mutation has an associated handler function. When a user types into an input, an event is triggered, the handler updates the state, and the component re-renders with the new value.
Why Use Controlled Components?
- Instant Validation: You can check if an input is valid on every keystroke and show error messages immediately.
- Conditional UI: Disable the 'Submit' button or show/hide fields based on the current value of another input.
- Input Formatting: Automatically format inputs (like credit card numbers or phone numbers) as the user types.
- Predictability: Since the state holds the data, the UI and the data are always in sync.
Handling Multiple Inputs
Instead of creating separate handlers for every field, you can use a single change handler by leveraging the name attribute of the HTML elements.