Controlled vs Uncontrolled

Pascual Vila
Frontend Instructor.
A controlled form in React is one whose value is managed through React's state. In contrast, an uncontrolled form manages its own state through references (ref).
Controlled Form:
In a controlled form, each input has a value managed by React through state.
{`import React, { useState } from "react";
function ControlledForm() {
const [name, setName] = useState("");
const handleChange = (event) => {
setName(event.target.value);
};
return (
<form>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;`}
Uncontrolled Form:
In an uncontrolled form, references (ref) are used to directly access the values of form fields.
{`import React, { useRef } from "react";
function UncontrolledForm() {
const nameRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
alert("Name entered: " + nameRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} />
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;`}