Careeroza
Uncontrolled Inputs
useRef or FormData
Example
The DOM keeps the value; you read it only when needed (on submit). Less code, but React does not know the value while typing.
export default function App() {
const handleSubmit = (e) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.target));
alert(JSON.stringify(data));
};
return (
<form onSubmit={handleSubmit}>
<input name="city" defaultValue="Pune" />
<input name="pin" placeholder="PIN" />
<button>Send</button>
</form>
);
}Result
Controlled vs Uncontrolled
| Controlled | Uncontrolled | |
|---|---|---|
| Value lives in | React state | the DOM |
| Read value | any time from state | ref / FormData on submit |
| Instant validation, formatting | easy | harder |
| Initial value | value | defaultValue |