Tell me about the differences between controlled and uncontrolled components in React.
sobes.tech AI
Answer from AI
Controlled components manage their state via useState (or class-based this.state) and receive data and callback functions through props. For example, form state is stored in React's state and updated via onChange input handlers.
Uncontrolled components store their state within the DOM. To access their value, useRef (or class-based React.createRef) is used to get a reference to the DOM element. The value of form elements, for example, is retrieved directly from the DOM upon submit.
| Characteristic | Controlled component | Uncontrolled component |
|---|---|---|
| State management | React State (useState) |
DOM |
| Access to value | Via state and props | Via Refs (useRef) |
| Update | Reactive, on every change | On explicit action (e.g., submit) |
| Validation | In React logic | Via standard HTML API or manually after obtaining the value |
Example of a controlled component:
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
}
return (
<input type="text" value={value} onChange={handleChange} />
);
}
Example of an uncontrolled component:
import React, { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef(null);
const handleClick = () => {
alert('Input value: ' + inputRef.current.value);
}
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Get value</button>
</>
);
}
The choice between them depends on the complexity of the logic and the need for instant reaction to input changes. Controlled components are preferable for complex forms and real-time validation. Uncontrolled components are convenient for simple forms or when integrating with third-party DOM libraries.