Benefits: Validation and Formatting On-the-Fly
What you'll learn: How controlled components let you transform and validate user input before it ever reaches your state.
The Core Idea
Because your onChange handler sits between the user's keystroke and your setState call, you have complete control over what actually gets stored. You can reject invalid characters, format text automatically, enforce length limits, or transform input—all in real-time as the user types.
Think of it like a security checkpoint at an airport: passengers (user input) must pass through screening (your onChange logic) before they can board the plane (your state). Only approved items get through.
How It Works
In the standard controlled pattern:
- User types →
onChangefires - Your code decides what to do with
event.target.value - You call
setStatewith the transformed value - React re-renders with the cleaned input
function PhoneInput() {
const [phone, setPhone] = useState('');
function handleChange(event) {
const input = event.target.value;
// Only allow digits, limit to 10 characters
const cleaned = input.replace(/\D/g, '').slice(0, 10);
setPhone(cleaned);
}
return <input value={phone} onChange={handleChange} />;
}
If the user types "555-abc-1234", only "5551234" reaches your state. The input field instantly shows the cleaned version because value={phone} reflects your state, not what they typed.
Why This Matters
You get instant validation without waiting for form submission. You can uppercase text automatically, add currency formatting, prevent spaces in usernames—whatever your app needs. The user sees the formatted result immediately, creating clear feedback about what's accepted.
Key Takeaway: The onChange handler is your gatekeeper—transform, validate, or reject input before calling setState, and the single source of truth ensures the user always sees the result of your rules.