Controlled Forms
Controlled Forms
A Controlled Component is a form element whose value is controlled entirely by React state. This is the standard, recommended way to build forms in React.
In a controlled component, the HTML element does not maintain its own internal state. Instead, React is the “single source of truth.”
How it works
To create a controlled input, you must do two things:
- Pass a React state variable to the input’s
valueprop. - Pass an updater function to the input’s
onChangeevent handler.
import { useState } from 'react';
function ControlledInput() {
// 1. Create the state
const [name, setName] = useState('');
// 2. Handle changes
const handleChange = (event) => {
setName(event.target.value);
};
return (
<form>
<label>
Name:
<input
type="text"
value={name} // The input displays whatever is in state
onChange={handleChange} // Typing updates the state
/>
</label>
<p>You typed: {name}</p>
</form>
);
}
The Data Flow
- The user presses a key (e.g., ‘A’).
- The browser fires the
onChangeevent. - React calls your
handleChangefunction. - You call
setName('A'), updating the state. - React re-renders the component.
- The
<input>receivesvalue={'A'}and updates what is shown on screen.
Why use Controlled Components?
Because React always knows the exact value of the input, controlled components allow you to implement complex logic easily:
- Instant Validation: You can validate an email address on every keystroke and show a red border immediately if it’s invalid.
- Conditional Submit Buttons: You can easily disable the “Submit” button if
name === ''. - Input Formatting: You can format data as the user types (e.g., automatically inserting hyphens into a credit card number or converting all text to uppercase).
Drawbacks
The primary drawback of controlled components is that they cause the component to re-render on every single keystroke.
For a simple login form, this is perfectly fine. However, if you have a massive form with 50 inputs inside a heavy parent component, re-rendering the entire component 50 times while the user types their name can cause noticeable lag. (This is where Uncontrolled Components or libraries like React Hook Form come in).
Interview Questions
Q: What is a “controlled” input in React?
A: An input element whose value is completely dictated by React state. The React state acts as the “single source of truth”, and the input physically cannot update on the screen unless the onChange handler successfully updates the state.