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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.