What are Controlled Components in React?
In React, Controlled Components are form elements (like <input>
, <textarea>
, or <select>
) whose values are controlled by the React state rather than the DOM itself.
In a controlled component:
- The input form element's value is set by the state.
- Any user interaction (like typing) triggers an event handler (usually
onChange
) that updates the state. - The UI always reflects the latest state, making the data flow predictable and easier to manage.
Example:
import { useState } from "react"; function ControlledInput() { const [name, setName] = useState(""); const handleChange = (event) => { setName(event.target.value); }; return ( <div> <input type="text" value={name} onChange={handleChange} /> <p>Your name: {name}</p> </div> ); }
Here:
- The
value
of the input is tied to thename
state. - As the user types,
handleChange
updates the state. - The displayed input and paragraph always stay in sync with
name
.
Benefits of Controlled Components:
- Single Source of Truth: The React state is the only place where the input value lives.
- Easier Validation: You can validate input data before updating the UI.
- Predictable Behavior: Since React controls the input, the behavior is more consistent.
- Enhanced Features: You can easily implement features like instant field validation, conditional disabling, or dynamic form fields.