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. React sets an initial value and then steps back until you read it.

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>
  )
}

Type a few characters and submit. The console should log whatever is currently in the field, including your edits. React did not re-render on every keystroke.

defaultValue supplies the initial value. Editing after that belongs to the DOM. Changing the defaultValue prop later does not replace the current field value. The browser already owns what the user typed.

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. Less state means less code.

Use controlled state when another part of the interface needs the current value, such as a live preview, character count, or dependent field. If the submit button should disable when the field is empty, you need React to know the current text on every keystroke.

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. Mixing them leads to warnings and confusing behavior.

My default is controlled inputs for anything interactive beyond a simple submit form. Uncontrolled inputs are fine when the DOM can hold the value until you read it once.

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