Events and forms
Know when an input can stay uncontrolled
Let the DOM hold an initial value when React does not need to render every edit.
An uncontrolled input keeps its current value in the DOM instead of React state.
function SearchForm() {
function handleSubmit(event) {
event.preventDefault()
const data = new FormData(event.currentTarget)
console.log(data.get('query'))
}
return (
<form onSubmit={handleSubmit}>
<label>
Search
<input name="query" defaultValue="React" />
</label>
<button type="submit">Search</button>
</form>
)
}
defaultValue supplies the initial value. Editing after that belongs to the DOM. Changing the defaultValue prop later does not replace the current field value.
Use an uncontrolled input when the value is needed only on submission and the rest of the interface does not react to every edit. Native forms and FormData work well here.
Use controlled state when another part of the interface needs the current value, such as a live preview, character count, or dependent field.
File inputs are uncontrolled because browser security rules prevent application code from setting a local file path.
Do not mix value and defaultValue. Choose which layer owns the current value.
Change the default prop after typing and observe that the DOM keeps the edit. Then rebuild the same field as controlled state and compare the behavior.
Lesson completed