Events and forms

Control an input with state

Make React state the current source of truth by pairing the input value with an onChange handler.

A controlled input gets its current value from React state.

function TaskForm() {
  const [title, setTitle] = useState('')

  return (
    <label>
      Task title
      <input
        name="title"
        value={title}
        onChange={event => setTitle(event.target.value)}
      />
    </label>
  )
}

Each edit follows the React cycle:

  1. The browser reports the edit and React calls the onChange handler.
  2. The handler requests a state update.
  3. React renders with the new title.
  4. The input receives that value.

State is the source of truth. This makes it easy to display a character count, format a value, or disable submission according to the same data.

Do not pass value without onChange unless the input is intentionally read-only. React will keep restoring the prop value, so typing appears broken.

Initialize text inputs with a string, usually ''. Switching between undefined and a string changes between uncontrolled and controlled behavior and produces warnings.

Controlling every keystroke causes the owner component to render. Keep state close to the form so unrelated expensive sections do not rerender. Optimize only after measuring a real problem.

Add a live character count and confirm the input, count, and state always agree.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →