Controlled Components: React Components that control the state of form elements via state or props, i.e., every state mutation will have an associated handler function.
Characteristics
- Value controlled by state - element value is bound to state variable
- Requires event handler - To update the state you need event handler
- Predictable - Since the component state represents the input value, the component is predictable and easy to debug
- React Handles the input data and doesn't rely on DOM to keep track of the current input value
import React, { useState } from 'react';
function ControlledForm() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form>
<input
type="text"
value={value}
onChange={handleChange}
/>
</form>
);
}
Uncontrolled Components: React Component where DOM itself handles the form element's state. React accesses the input value via ref, which stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
Characteristics
- Value controlled by DOM - The input field's value is not bound to a state variable.
- Uses Ref to access a value or to get the value of input element when needed
- They are simpler to set up if you don't need real-time control over input.
- Suitable for scenarios where react state isn't required to control the input.
import React, { useRef } from 'react';
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (event) => {
event.preventDefault();
alert('Input Value: ' + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
Here's a comparison table between controlled and uncontrolled components:
When to use when
Controlled - for real-time validations, input formatting, or immediate feedback.
Uncontrolled - used for simple use cases like file uploads pre-filled form value isn't frequent or needs to be deferred until form submission.
Top comments (1)
You don't need refs to get the data, you can get it directly from the form data in the onChange or onSubmit events.