Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

14. What are controlled and uncontrolled components in React and what are the differences between them?

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.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz