Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 132 ยท State and Events

Controlled Inputs and Forms

Learn controlled inputs in React - text, checkbox, radio, select and textarea, one handler for many fields, submit handling, derived validation and controlled vs uncontrolled.

A form field is one of the few places where the browser keeps its own state. If you type into a plain <input>, the DOM node remembers the text; your JavaScript only finds out when it asks. React flips this around. In a controlled input, React state is the single source of truth: the input shows whatever your state says, and every keystroke goes through your code before it appears on screen.

That sounds like extra work, and it is a little. In return you get instant validation, formatting while typing, fields that depend on each other, and a form whose entire content is one plain JavaScript object you can inspect, reset or send to a server. This lesson builds that skill from a single text box to a complete form, and ends with the difference between controlled and uncontrolled inputs. It builds on useState and objects and arrays in state.

A controlled text input

A controlled input has two props that work as a pair: value (what to show) and onChange (what to do when the user types). The loop looks like this:

  1. The user presses a key.
  2. The browser fires an input event, React calls your onChange handler.
  3. The handler reads event.target.value and calls the state setter.
  4. React re-renders, and the input gets the new value.
A controlled text input

The paragraph below the input updates on every keystroke, with no extra code, because it is just a function of name. That is the payoff of controlled inputs: the text exists in your state, so anything can use it during render.

React's onChange is not the native change event. The native one fires when the field loses focus; React's fires on every edit, like the native input event. Always use onChange with controlled inputs.

If you pass value without onChange, React makes the input read-only and logs a warning. If you need a read-only field on purpose, add readOnly. If you want an input that starts with a value but stays editable without React tracking it, use defaultValue (see the end of this lesson).

Why the input "pushes back"

Because React controls the value, an input whose handler does not update state cannot be edited at all. The user types, React renders, and the old value is put back. You can use this on purpose to filter what is allowed.

Filtering input: digits only

Try typing letters: nothing appears, because the handler throws them away before they reach state. State holds the clean digits; the formatted version is computed during render. This is a good habit: store the simplest representation and derive the pretty one.

Every field type has its own value prop

Text-like inputs use value. Checkboxes and radios use checked. A <select> uses value on the <select> itself, not selected on the options. And <textarea> takes value as well, instead of children as in plain HTML.

Element State prop Read from the event
<input type="text">, email, number, date... value event.target.value
<input type="checkbox"> checked event.target.checked
<input type="radio"> checked (per radio) event.target.value
<select> value on the select event.target.value
<select multiple> value as an array event.target.selectedOptions
<textarea> value event.target.value
Checkbox, radio, select and textarea

The <pre> at the bottom shows the point of controlled forms: the whole form is one snapshot of state that you can print, validate or send. Notice that the radios share a name (so the browser groups them for keyboard navigation) but each decides checked from the single plan state.

One handler for many fields

A form with ten fields does not need ten useState calls and ten handlers. Keep one object, give every input a name, and write one handler that updates the key matching event.target.name. This uses a computed property name and the immutable update pattern from the previous lesson.

JSX
function handleChange(event) {
  const { name, type, value, checked } = event.target;
  setForm((previous) => ({
    ...previous,
    [name]: type === 'checkbox' ? checked : value,
  }));
}

Two details matter. First, the functional update (previous => ...) means rapid events never overwrite each other's changes (see how state updates work). Second, [name] is a computed key: if the input's name is "email", the object gets an email property.

A sign-up form with one handler and submit

Look at what handleSubmit does. The browser's default action for a form submission is to navigate to another page, which would reload everything. event.preventDefault() stops that so your code can handle the data. Because every value is already in state, there is no need to read the DOM at submit time. The sandbox preview would block a real network post anyway, so the demo just prints the object. In a real app you would send form to a server here.

Two small traps worth knowing:

  • Number inputs give strings. Even type="number" yields "42", not 42. Convert at the boundary (Number(form.age)), and keep the empty string as the "nothing typed" value so users can clear the field.
  • Use a <form> and a submit button, not a click handler on a plain button. Then pressing Enter in a field submits the form, and assistive technology announces it as a form.

Derived validation

When the form is state, validation is a calculation. Do not store errors in state and try to keep them synchronized with the values; compute them during render from the values. Choosing a state structure explains why: anything you can compute from other state should not be state.

Validation computed during render

Press Save with empty fields and two messages appear (the passwords match, so the third rule stays quiet). Type a valid password twice and they vanish immediately, without any "clear the errors" code. The touched flag is the only extra state: it decides when to show errors, which is a UX choice. Form validation goes deeper on timing, accessibility and multi-step forms.

Controlled versus uncontrolled

An uncontrolled input does not get a value. The DOM keeps the text; you read it when you need it, with a ref or from the FormData of the submit event. You can give it a starting text with defaultValue (or defaultChecked), which is used only on the first render.

JSX
function QuickSearch() {
  function handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    console.log(data.get('query'));
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="query" defaultValue="react" />
      <button type="submit">Search</button>
    </form>
  );
}
Controlled Uncontrolled
Source of truth React state The DOM
Value on each keystroke Available in state Not available unless you listen
Validate or format while typing Easy Awkward
Disable a button until valid Easy Needs extra events
Re-renders per keystroke One for the form component None
Best for Most interactive forms Simple submit-only forms, file inputs

Neither is "right". Start controlled when the UI reacts to what is being typed; reach for uncontrolled when you only need the final data. Uncontrolled forms and file inputs covers that style, and React 19's form actions make the uncontrolled style much nicer.

Never switch one input between controlled and uncontrolled. If value is undefined on the first render and a string later, React warns that the component changed from uncontrolled to controlled. Initialise state with '', not undefined or null.

Re-render cost

Each keystroke re-renders the component that owns the state and its children. For a normal form this is a few microseconds. If a big form feels sluggish, move each field's state down into a small component, or memoize the expensive siblings, before reaching for tricks. Measure first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you pass to a controlled checkbox to show whether it is ticked?

    Checkboxes and radios use the checked prop. value is the text submitted with the form, not the on/off state.
  2. 2. You render <input value={text} /> with no onChange. What happens?

    A value without an onChange makes the field effectively read-only, because React keeps restoring the old value. React logs a warning suggesting onChange or readOnly.
  3. 3. How does one handler update many fields in a form object?

    Each input has a name; the handler copies the previous object and replaces the key given by the input's name, without mutating state.
  4. 4. Where should the list of validation errors normally live?

    Errors are derived from values, so storing them separately risks the two getting out of sync. Compute them while rendering.
  5. 5. Why call event.preventDefault() in a submit handler?

    The default action of a form submit is a page navigation. preventDefault cancels it so your JavaScript can handle the data.

Summary

  • A controlled input gets value (or checked) and onChange; React state is the single source of truth, and each keystroke is a state update.
  • Text, textarea and select use value; checkbox and radio use checked; read event.target.value or event.target.checked.
  • Give inputs a name and use one handler with a computed key and a functional update to manage many fields.
  • Use a real <form> with onSubmit and event.preventDefault(); number inputs still produce strings.
  • Derive validation and formatted values during render instead of storing them.
  • Uncontrolled inputs (defaultValue, FormData, refs) are fine for submit-only forms; never flip one input between the two modes.

Next: Choosing a State Structure