In React, Controlled Components and Uncontrolled Components are both approaches to handling form inputs, but they manage data differently.
Controlled Components
Controlled components represent a pattern in React where form data is managed by the component's state. Specifically, whenever the field's value changes, we update the component's state through an event handler (typically onChange). The component's state is then used as the value for the input field, ensuring that the component's state is the single source of truth for the data.
Example:
jsxclass ControlledComponent extends React.Component { constructor(props) { super(props); this.state = {value: ''}; } handleChange = (event) => { this.setState({value: event.target.value}); } render() { return ( <form> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> </form> ); } }
In the above example, the value of the <input> is always determined by this.state.value, and whenever the user types, the handleChange function updates the state, ensuring the UI consistently reflects the current state.
Uncontrolled Components
Uncontrolled components represent another pattern where form data is handled directly by the DOM rather than by React state. This mirrors traditional HTML form behavior. In uncontrolled components, we typically use ref to access form data from DOM nodes instead of writing event handlers for each state change.
Example:
jsxclass UncontrolledComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } handleSubmit = (event) => { alert('A name was submitted: ' + this.inputRef.current.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.inputRef} /> </label> <button type="submit">Submit</button> </form> ); } }
In the above example, the <input> is not controlled by state but accessed via ref to retrieve its value from the DOM node.
Summary
- Controlled components provide better control over form behavior because the component's state serves as the true source of data.
- Uncontrolled components relinquish immediate control over form state, resulting in cleaner component code, but may make managing form state more challenging, especially in complex form interactions.
In practical development, controlled components are often the preferred method as they align better with React's data flow concepts, making state management clearer and more predictable. However, for simple forms or when integrating with third-party DOM libraries, uncontrolled components can also be a viable option.