Controlled inputs

Topic 1 of 3 in Forms6 min readIntermediateFree course

Overview

Form inputs have their own internal state in the browser: a text field remembers what you typed. In React you usually want your state to be in charge instead, so the UI always reflects your data. An input whose value comes from React state is called a controlled input.

A controlled text input

JSX
function NameField() {
  const [name, setName] = useState('');

  return (
    <>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <p>Hello, {name || 'stranger'}!</p>
    </>
  );
}

State holds name = ‘Asha’. It flows into the input’s value prop, which shows the state. When the user types, onChange calls setName with e.target.value, updating the state, which flows back into the input.

Every keystroke goes through a loop: the user types, onChange fires, you call setName, React re-renders, and the input displays the new name. Because your code sits in the middle of that loop, you can transform or validate the value as it’s typed:

JSX
// Force uppercase coupon codes, max 10 characters
<input
  value={coupon}
  onChange={(e) => setCoupon(e.target.value.toUpperCase().slice(0, 10))}
/>

The read-only trap

If you pass value without onChange, React makes the input read-only — typing does nothing — and logs a warning: “You provided a value prop to a form field without an onChange handler.” Either add onChange, use readOnly deliberately, or use defaultValue (uncontrolled, below).

Other input types

Textarea

In React, <textarea> uses a value prop instead of children:

JSX
<textarea value={bio} onChange={(e) => setBio(e.target.value)} rows={4} />

Checkbox

Checkboxes use checked and e.target.checked:

JSX
const [agreed, setAgreed] = useState(false);

<label>
  <input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />
  I agree to the terms
</label>

Select

<select> takes a value — no need for selected on options:

JSX
const [level, setLevel] = useState('beginner');

<select value={level} onChange={(e) => setLevel(e.target.value)}>
  <option value="beginner">Beginner</option>
  <option value="intermediate">Intermediate</option>
  <option value="advanced">Advanced</option>
</select>

For a multi-select, add multiple and pass an array: value={['a', 'b']}, reading the selection with Array.from(e.target.selectedOptions, (o) => o.value).

Radio buttons

A radio group is one piece of state; each radio is checked when its value matches:

JSX
const [plan, setPlan] = useState('monthly');

{['monthly', 'yearly'].map((option) => (
  <label key={option}>
    <input
      type="radio"
      name="plan"
      value={option}
      checked={plan === option}
      onChange={(e) => setPlan(e.target.value)}
    />
    {option}
  </label>
))}

Numbers

e.target.value is always a string, even for type="number". Convert it when you need a number, and be careful with the empty string while the user is mid-edit:

JSX
<input
  type="number"
  value={qty}
  onChange={(e) => setQty(e.target.value === '' ? '' : Number(e.target.value))}
/>

Many fields, one handler

Store the form in one object and use the input’s name to update the right field:

JSX
function SignupForm() {
  const [form, setForm] = useState({ name: '', email: '', newsletter: true });

  function handleChange(e) {
    const { name, type, value, checked } = e.target;
    setForm({ ...form, [name]: type === 'checkbox' ? checked : value });
  }

  return (
    <form>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="email" type="email" value={form.email} onChange={handleChange} />
      <label>
        <input name="newsletter" type="checkbox" checked={form.newsletter} onChange={handleChange} />
        Send me course updates
      </label>
    </form>
  );
}

Controlled must stay controlled

React warns when an input switches from uncontrolled to controlled: “A component is changing an uncontrolled input to be controlled.” This happens when value starts as undefined and later becomes a string:

JSX
const [user, setUser] = useState({});           // user.name is undefined at first
<input value={user.name} onChange={…} />        // ✗ starts uncontrolled

<input value={user.name ?? ''} onChange={…} />  // ✓ always a string

Always initialise text state with '', never undefined or null.

Uncontrolled inputs

Not every input needs state. If you only need the values when the form is submitted, let the browser keep them and read them with FormData:

JSX
function ContactForm({ onSend }) {
  function handleSubmit(e) {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.currentTarget));
    onSend(data);              // { name: '…', message: '…' }
    e.currentTarget.reset();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" defaultValue="" required />
      <textarea name="message" defaultValue="" required />
      <button type="submit">Send</button>
    </form>
  );
}

Use defaultValue (or defaultChecked) to set the initial value of an uncontrolled input.

Use controlled inputs when… Uncontrolled is fine when…
the UI reacts as the user types (live search, character counters) you only need values on submit
you validate or format on each keystroke the browser’s built-in validation is enough
other components depend on the value the form is simple and self-contained
you need to reset or set values from code —

React 19’s form actions build on uncontrolled forms and FormData — that’s the next lesson.

Performance note: a controlled input re-renders its component on every keystroke. That’s normally instant. If a big list below the input re-renders slowly as you type, see Transitions and deferred values.

Exercise

A course filter form

Build CourseFilters({ onChange }) with controlled inputs: a text search, a <select> for level (All, Beginner, Intermediate, Advanced), a “Free only” checkbox, and radio buttons for sort order (title or newest). Keep all values in one state object, and call onChange(filters) with the new filters every time one changes. Add a “Reset” button that restores the defaults.

JavaScript
import { useState } from 'react';

const defaults = { q: '', level: 'all', freeOnly: false, sort: 'title' };

export function CourseFilters({ onChange }) {
  // your code here
}

Summary

  • A controlled input gets its value (or checked) from state and updates that state in onChange.
  • If you pass value without onChange, the input becomes read-only and React warns.
  • Checkboxes use checked; selects and textareas use value; radio groups compare checked={state === option}.
  • Never switch an input between controlled and uncontrolled — don’t let value become undefined.
  • Uncontrolled inputs (with defaultValue and FormData) are simpler when you only need the values on submit.