What is an uncontrolled form input, and how does it differ from a controlled one?
Short answer
An uncontrolled input keeps its own value internally in the actual HTML element, similar to how forms worked before React existed.
Advertisement
AModel answer
An uncontrolled input keeps its own value internally in the actual HTML element, similar to how forms worked before React existed. Instead of tracking every keystroke in state, you read the input's current value only when you need it, usually using a ref, such as when the form is submitted.
function NameInput() {
const inputRef = useRef(null);
function handleSubmit() {
alert(`Name entered: ${inputRef.current.value}`);
}
return (
<>
<input ref={inputRef} defaultValue="" />
<button onClick={handleSubmit}>Submit</button>
</>
);
}Real-world example
A simple contact form reads the message field's value only when the user clicks submit, using an uncontrolled input with a ref, since there is no need to react to every single keystroke as it happens.
Likely follow-ups
- When would you choose an uncontrolled input over a controlled one?
- What does the defaultValue prop do differently from the value prop?
Related topics