Controlled and Uncontrolled Components in React
In React, components can be classified as controlled or uncontrolled based on how they manage their state and data.
Controlled Components
Controlled components are those where the state is managed by React.
The component’s value is controlled by React’s state, and changes are handled via event handlers.
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}
/>
);
}
Uncontrolled Components
Uncontrolled components are those where the state is managed by the DOM itself, and React does not control the component’s value.
Instead, you use refs to access the DOM element directly.
import React, { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => {
alert('Input value: ' + inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
Key Differences
Feature | Controlled Components | Uncontrolled Components |
---|---|---|
State Management | Managed by React state | Managed by the DOM |
Data Access | Accessed via state | Accessed via refs |
Use Case | Forms, dynamic inputs | Simple inputs, file uploads |
Performance | Slightly slower (due to re-renders) | Faster (no re-renders) |
Summary
Both controlled and uncontrolled components have their place in React development. Understanding their differences helps you write more efficient, maintainable, and scalable applications.
For most cases, controlled components are recommended due to their predictability, but if performance is a key factor, uncontrolled components may be the better choice.