1. Controlled Components in React
In a controlled component, React takes full control over the form inputs. The form data is stored in the component’s state, and any user interaction triggers updates to that state. The input value is always synced with the state, meaning React controls both the display and modification of the input’s value.
2. Key Characteristics:
onChange
).
import { useState } from 'react';
function ControlledComponent() {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
return (
Current Value: {inputValue}
);
}
In this case, the value of the input is bound to the component’s state (inputValue
). Any changes made by the user trigger the onChange
event handler to update the state.
3. Uncontrolled Components in React
In uncontrolled components, form input values are managed by the DOM itself rather than by React. Instead of maintaining the value in React state, you access the input value directly from the DOM when needed, usually by using refs (React.createRef()
or useRef
).
4. Key Characteristics:
import { useRef } from 'react';
function UncontrolledComponent() {
const inputRef = useRef();
const handleSubmit = () => {
alert(`Input Value: ${inputRef.current.value}`);
};
return (
);
}
Here, the input value is accessed via the inputRef
reference to the DOM element, without React controlling its state.
4. Differences Between Controlled and Uncontrolled Components
Data Management:
- Controlled Components: The data is stored and controlled in the React component’s state.
- Uncontrolled Components: The data is controlled by the DOM and accessed via refs.
Complexity:
- Controlled Components: Require more boilerplate for setting up state and event handlers.
- Uncontrolled Components: Simpler to implement for basic forms, but harder to maintain for more complex interactions.
Use Case:
- Controlled Components: Preferred when you need full control over the form’s behavior, validation, or real-time updates.
- Uncontrolled Components: Useful for simpler forms where you don’t need real-time validation or control over input.