In HTML, form elements like <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, we often want to have single source of truth - meaning React state should be the source of truth for form data.
A controlled component is a form element whose value is controlled by React state. The form element's value is set by state, and changes are handled through event handlers that update that state.
Why Use Controlled Components?
- Single Source of Truth: The React state is always the current value
- Validation: You can validate input on every keystroke
- Conditional Disabling: Easily disable submit buttons based on form validity
- Enforced Input Formats: Format input as the user types (e.g., phone numbers)
- Dynamic Inputs: React to changes immediately
Basic Example
jsximport { useState } from 'react'; function NameForm() { const [name, setName] = useState(''); function handleChange(e) { setName(e.target.value); } return ( <input type="text" value={name} // Controlled by state onChange={handleChange} // Updates state /> ); }
The key insight is that value={name} makes React the source of truth. The input will always display whatever is in name state.
The Data Flow
- User types in the input
onChangeevent fires with the new value- Event handler calls
setNamewithe.target.value - React re-renders the component
- Input displays the new value from state
This circular flow happens so fast it feels instantaneous, but understanding it is crucial for mastering forms in React.
š Learn more: Reacting to Input with State