← React Beginner Questions - Set 2 Q12
React Beginner Questions - Set 2
One input, two philosophies: React owns the value, or the DOM owns it and you read it on demand.
import { useState, useRef } from 'react';
export default function Form() {
const [controlled, setControlled] = useState('');
const uncontrolledRef = useRef(null);
function submit(e) {
e.preventDefault();
console.log('controlled :', controlled);
console.log('uncontrolled:', uncontrolledRef.current.value);
}
return (
<form onSubmit={submit}>
<input value={controlled} onChange={e => setControlled(e.target.value)} />
<input defaultValue="initial" ref={uncontrolledRef} />
<button type="submit">Send</button>
</form>
);
}