In this post we’re going to discuss Controlled and Uncontrolled components in React.
Controlled
A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component “controls” it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a “dumb component”.
// Controlled class Form extends Component { constructor() { super(); this.state = { name: '', }; } handleNameChange = (event) => { this.setState({ name: event.target.value }); }; render() { return ( <div> <input type="text" value={this.state.name} onChange={this.handleNameChange} /> </div> ); } }
Uncontrolled
A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
// Uncontrolled class Form extends Component { handleSubmitClick = () => { const name = this._name.value; // do something with `name` } render() { return ( <div> <input type="text" ref={input => this._name = input} /> <button onClick={this.handleSubmitClick}>Sign up</button> </div> ); } }
In most cases you should use controlled components but that doesn’t mean you should use them all the time, like if:
- Your form is very simple and doesn’t need any instant validation?
- Even if any validations are needed, they are done only when the form is submitted?
- Values need to be retrieved only on “submit”. No fields are dependent on any other field(s)?