React › Design Patterns in React
What is the controlled component pattern and why is it considered a best practice for forms?
IntermediateAnswer
In a controlled component, the form input's value is always driven by React state, meaning React is the single source of truth for what the input shows. This makes it easy to validate, format, or react to changes immediately, since every keystroke updates the component's own state right away.
function EmailInput() {
const [email, setEmail] = useState('');
return (
<input
value={email}
onChange={(e) => setEmail(e.target.value.toLowerCase())}
/>
);
}Real-world example A signup form automatically converts every email address a user types into lowercase letters as they type, since the input's value is fully controlled by React state that can be transformed on every keystroke.