Controlled components in React are form components whose state is managed by React. The value of these components is passed through props, and any changes to the value are handled by a function. Uncontrolled components store their state internally using refs.
Controlled components:
class ControlledComponent extends React.Component { constructor(props) { super(props); this.state = { value: '' }; } handleChange = (event) => { this.setState({ value: event.target.value }); } render() { return ( <input type="text" value={this.state.value} onChange={this.handleChange} /> ); } }
Uncontrolled components:
class UncontrolledComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } handleSubmit = (event) => { event.preventDefault(); alert('Submitted value: ' + this.inputRef.current.value); } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref={this.inputRef} /> <button type="submit">Submit</button> </form> ); } }
The main difference is that in controlled components, React manages the form state, while in uncontrolled components, the state is managed by the DOM.