What Are Controlled Components?
So you've learned about handling events and managing state in React. Now let's talk about forms. When you work with form elements like inputs, checkboxes, or selects, you need a way to manage their values. Controlled components are React's elegant solution to this problem.
Think of a controlled component like a puppet with strings attached. React holds the strings (the state), and the form element just follows along. The form element's value is controlled by React state, not by the DOM itself. Every keystroke, every change goes through React first.
Managing Input with State
To create a controlled component, you bind the form element's value to a state variable. When the user types something, you update the state with the onChange handler. The input then displays whatever's in the state. It's a beautiful two-way street.
Here's the pattern: initialize state with a default value, set the input's value to that state, and update state on change. React becomes the single source of truth for your form data.
import { useState } from "react";
function ControlledInput() {
const [name, setName] = useState("");
return (
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
);
}
Try it Yourself โ
Two-Way Data Binding
Here's where it gets really cool. Controlled components give you two-way data binding. The data flows from state to the input (displaying the value), and from the input back to state (updating on change). It's like having a conversation between your component and the form element.
This means you can instantly react to user input, validate data as it's typed, or even transform it before displaying. Try typing in the input above โ you'll see React updates immediately.
function TwoWayBinding() {
const [email, setEmail] = useState("");
const handleChange = (e) => {
setEmail(e.target.value.toLowerCase());
};
return (
<div>
<input value={email} onChange={handleChange} />
<p>You typed: {email}</p>
</div>
);
}
Try it Yourself โ
Benefits of Controlled Components
Trust me, once you get the hang of controlled components, you'll never want to go back. They give you instant validation โ you can check if an email is valid as the user types. They let you enforce format constraints, like only allowing numbers in a phone field.
But there's more. You can disable submit buttons until the form is valid, dynamically validate fields based on other inputs, and implement complex form logic. Since React has complete control over the form state, you can do anything you imagine with your form data.