Controlled components use the React state to manage form data, while uncontrolled components use the DOM.
Controlled components are usually preferable because they give a single source of form data truth, making it easy to maintain, validate, and submit.
Controlled components
const ControlledInputForm = () => {
const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};return (
<form onSubmit={handleSubmit}>
input type="text" value={value} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
};
UnControlled components
const UncontrolledInputForm = () => {
const inputRef = useRef(null);const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
};