Forms

Controlled and uncontrolled inputs, and validation basics.

Builds on State, Refs.

Back in chapter 1 the DOM's statefulness was the problem: a text input remembers what the user typed whether your code knows about it or not. Forms are where that old problem comes back. Every input has a value that lives in the DOM, and you may also want it in React state. Two places can hold one value, so you have to decide who owns it.

That decision is controlled versus uncontrolled, and it's most of what there is to know about forms in React. This chapter covers both, when each fits, submitting and resetting (including two small React 19.3 changes), and enough validation to build a decent form by hand. It relies on state and refs.

The problem: who owns the value?#

Two components, two common mistakes. Try typing in both inputs, then press each button.

Two ways to confuse React about an input
import { useState } from "react";

function FrozenInput() {
  const [name, setName] = useState("Grace");
  return (
    <p>
      <input value={name} /> <button onClick={() => setName("Ada")}>Set to Ada</button>
    </p>
  );
}

function IgnoredDefault() {
  const [name, setName] = useState("Grace");
  return (
    <p>
      <input defaultValue={name} /> <button onClick={() => setName("Ada")}>Set to Ada</button> state: {name}
    </p>
  );
}

export default function App() {
  return (
    <>
      <FrozenInput />
      <IgnoredDefault />
    </>
  );
}
Nothing logged yet.

The first input won't take your typing. It has value but no onChange, so React owns the value and nobody ever changes it: every keystroke is undone on the next commit. React warns about exactly this in the console. The button works, because it changes the state.

The second input takes your typing but ignores the button. defaultValue is only the starting value; after mount the DOM owns the input, and later changes to the prop don't touch it. The state and the screen now disagree.

Each input is fine on its own terms. The bugs come from mixing them up. So, the two models properly.

Controlled inputs#

A controlled input gets its value from React state, and every change goes through your handler. Two props, always together: value and onChange.

A controlled form with a live preview
import { useState } from "react";
import { Rendered } from "guide-tools";

export default function App() {
  const [title, setTitle] = useState("Crafting Interpreters");
  const [tag, setTag] = useState("fundamentals");
  const [read, setRead] = useState(false);
  const [notes, setNotes] = useState("");

  return (
    <Rendered label="EditBook">
      <form style={{ display: "grid", gap: 8, maxWidth: 340 }}>
        <label>
          Title <input value={title} onChange={(e) => setTitle(e.target.value)} />
        </label>
        <label>
          Tag{" "}
          <select value={tag} onChange={(e) => setTag(e.target.value)}>
            <option value="fundamentals">fundamentals</option>
            <option value="craft">craft</option>
            <option value="systems">systems</option>
          </select>
        </label>
        <label>
          <input type="checkbox" checked={read} onChange={(e) => setRead(e.target.checked)} /> Read
        </label>
        <label>
          Notes ({notes.length}/80)
          <textarea value={notes} maxLength={80} onChange={(e) => setNotes(e.target.value)} />
        </label>
      </form>
      <p>
        Preview: <strong>{title || "Untitled"}</strong> [{tag}] {read ? "read" : "to read"}
      </p>
    </Rendered>
  );
}

Notice three things:

  • React normalizes the element APIs. A <select> takes value (no selected on options) and <textarea> takes value (no children). Checkboxes and radios use checked, read from e.target.checked.
  • onChange fires on every keystroke. The DOM's native change event on a text input only fires when it loses focus. React's onChange is wired to the input event instead, which is what you want for controlled state.
  • The whole component re-renders per keystroke. Watch the render counter. That's normally cheap, and it's what makes the live preview and the character count possible.

Here's that loop step by step, with the uncontrolled path for comparison:

Controlled versus uncontrolled, one keystroke
ControlledkeystrokeDOM input eventonChange(e)setName(...)rendervalue="Ada"commitinput.value = "Ada"screen shows stateUncontrolledkeystrokeDOM keeps the valueon submit:new FormData(form)
Step 1 of 6

A controlled input: React state is the source of truth, and the input renders value={name}. The user presses a key.

The payoff of the loop is that your handler decides what the value becomes. Uppercase it, strip non-digits from a phone number, or refuse input past a limit, and the DOM follows the state on commit.

Uncontrolled inputs#

An uncontrolled input keeps its value in the DOM, as plain HTML does. You give it a starting value with defaultValue (or defaultChecked for checkboxes and radios) and read the value when you need it. React doesn't re-render while the user types.

The cleanest way to read a whole form is FormData, the browser's own API for collecting named fields:

An uncontrolled form read with FormData
import { useState, type FormEvent } from "react";
import { Rendered } from "guide-tools";

type NewBook = { title: string; tag: string; read: boolean };

export default function App() {
  const [added, setAdded] = useState<NewBook[]>([]);

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault(); // stop the browser from navigating
    const data = new FormData(e.currentTarget);
    console.log(Object.fromEntries(data));
    const book = {
      title: String(data.get("title")),
      tag: String(data.get("tag")),
      read: data.get("read") === "on", // unchecked boxes are simply missing
    };
    setAdded((list) => [...list, book]);
    e.currentTarget.reset();
  }

  return (
    <Rendered label="AddBook">
      <form onSubmit={handleSubmit} style={{ display: "grid", gap: 8, maxWidth: 340 }}>
        <label>
          Title <input name="title" defaultValue="" />
        </label>
        <label>
          Tag{" "}
          <select name="tag" defaultValue="craft">
            <option value="fundamentals">fundamentals</option>
            <option value="craft">craft</option>
            <option value="systems">systems</option>
          </select>
        </label>
        <label>
          <input type="checkbox" name="read" /> Read
        </label>
        <button>Add</button>
      </form>
      <ul>
        {added.map((b, i) => (
          <li key={i}>
            {b.title} [{b.tag}] {b.read ? "read" : ""}
          </li>
        ))}
      </ul>
    </Rendered>
  );
}
Nothing logged yet.

Type a title: the render counter doesn't move. It changes once, on submit. Every field needs a name for FormData to see it.

For a single field you can also read the DOM node through a ref (inputRef.current.value), which is handy for "focus this and read it" cases like a search box. And some inputs can only be uncontrolled: <input type="file"> has a read-only value, so you always read its files from the event or a ref.

When each fits#

SituationReach for
Other UI depends on the value as it changes (preview, character count, a dependent field)Controlled
Formatting or restricting input while typing (masks, uppercase, digits only)Controlled
Validation as the user types, or enabling a button only when the form is validControlled
The value can change from outside (load a draft, "clear", undo)Controlled
You only need the values on submitUncontrolled
Large forms where a re-render per keystroke is measurableUncontrolled
File inputs, or wrapping a non-React widgetUncontrolled

Neither is "the React way". Controlled is more explicit and more flexible; uncontrolled is less code and less rendering. Mixed forms are normal too: most fields uncontrolled, one controlled field that drives a preview. Form libraries pick sides as well. React Hook Form, covered in URL and form state, is uncontrolled by default and reads fields through refs precisely to avoid re-rendering on every keystroke.

PredictValue without onChange

A teammate writes <input value={query} /> with const [query, setQuery] = useState(""), and no onChange. What happens when a user types "abc", and what does React print in development?

Submitting#

A form submits when the user presses Enter in a field or clicks a submit button (a <button> inside a form is type="submit" unless you say otherwise). Handle it on the form, not on the button, so both paths work:

  • Use onSubmit on the <form> and call e.preventDefault(), or the browser navigates and reloads the page.
  • Use e.currentTarget for the form. e.target is whatever element dispatched the event, and with nested or portaled content it isn't always the element you attached the handler to.

Which button submitted? React 19.3#

Forms often have two submit buttons: "Save" and "Save and add another", or "Approve" and "Reject". The browser records which button triggered the submit as submitter on the native SubmitEvent. Until React 19.3, React's synthetic submit event didn't copy it over, so you had to reach for e.nativeEvent.submitter. Since 19.3, e.submitter is on the React event too.

Reading the submitter
import { useState, type FormEvent } from "react";

export default function App() {
  const [log, setLog] = useState<string[]>([]);

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const submitter = (e as unknown as SubmitEvent).submitter as HTMLButtonElement | null;
    // Passing the submitter to FormData includes the button's own name and value.
    const data = new FormData(e.currentTarget, submitter);
    console.log("submitter:", submitter?.textContent, "intent:", data.get("intent"));
    const intent = data.get("intent");
    setLog((l) => [...l, `${data.get("title")} (${intent === "save-read" ? "read" : "to read"})`]);
    e.currentTarget.reset();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="title" defaultValue="Refactoring" />{" "}
      <button name="intent" value="save">Save</button>{" "}
      <button name="intent" value="save-read">Save as read</button>
      <ul>{log.map((line, i) => <li key={i}>{line}</li>)}</ul>
    </form>
  );
}
Nothing logged yet.

Click each button, then press Enter in the field. Enter submits with the first submit button as the submitter, which is worth knowing when you order buttons. The cast in the handler is only for TypeScript: depending on your @types/react version, the React event type may not declare submitter yet, while at runtime in 19.3 it's there. In older React versions, (e.nativeEvent as SubmitEvent).submitter works.

The second argument to new FormData(form, submitter) is a standard browser feature: it adds the clicked button's name and value to the data, just like a real HTML form submission would. React 19.3 also started passing the submitter that way when it builds FormData for form Actions.

Resetting#

A <button type="reset"> (or form.reset()) puts every uncontrolled field back to its default value. It can't touch your React state, so controlled fields need you to reset the state yourself, and the place to do it is the form's onReset handler, which fires for every reset.

There's a subtlety that makes the bug easy to miss: for a controlled input, React keeps the DOM's default value in sync with the current value. So a native reset on a controlled form usually looks like it did nothing at all. The exercise below shows it.

React 19.3 React itself sometimes resets forms: after a form Action succeeds, it resets the form's uncontrolled fields automatically. Before 19.3 that automatic reset didn't fire your onReset handler; since 19.3 it does, so code that cleans up on reset runs in both cases. Actions are covered in chapter 25.

Another reset tool you already know from state: change the key of the form (or the component holding the form's state) and React throws away the whole subtree and its state, then mounts a fresh one. That's the easiest way to reset a big controlled form, or to start over when the user switches to editing a different record.

Fix itReset that doesn't reset

The Reset button should put the name back to "Grace". Type " Hopper", then press Reset: nothing visible happens and the greeting keeps the edit. Fix it without removing the reset button. Press Check.

A controlled form with a reset button
import { useState } from "react";

const initialName = "Grace";

export default function App() {
  const [name, setName] = useState(initialName);
  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <label>
        Name <input value={name} onChange={(e) => setName(e.target.value)} />
      </label>{" "}
      <button type="reset">Reset</button>
      <p>Hello, {name}</p>
    </form>
  );
}

Validation basics#

Start with what the browser gives you for free. HTML constraint validation checks required, type="email", minLength, maxLength, min, max and pattern, blocks the submit, and shows a native message. It's accessible and needs no JavaScript. You can also query it: form.checkValidity(), input.validity.valueMissing, input.validationMessage, and input.setCustomValidity("...") for your own rules.

When you want your own error UI, add noValidate to the form to switch off the browser's bubbles (the validity APIs still work) and render errors yourself. A few rules keep hand-written validation sane:

  • Derive errors from values; don't store them. Errors are a function of the current values, so compute them during render. Storing them in state invites stale errors.
  • Don't yell while the user is typing. Show a field's error after it's been blurred ("touched") or after a submit attempt.
  • Wire errors for assistive tech. aria-invalid on the field and aria-describedby pointing at the message, with ids from useId.
  • Always validate on the server too. Client validation is for the user's convenience; anyone can send your endpoint anything.
Derived errors, shown after blur or submit
import { useId, useState, type FormEvent } from "react";

type Values = { email: string; password: string };

function validate(v: Values) {
  const errors: Partial<Record<keyof Values, string>> = {};
  if (!v.email) errors.email = "Email is required";
  else if (!/^\S+@\S+\.\S+$/.test(v.email)) errors.email = "Enter a valid email";
  if (v.password.length < 8) errors.password = "Use at least 8 characters";
  return errors;
}

export default function App() {
  const id = useId();
  const [values, setValues] = useState<Values>({ email: "", password: "" });
  const [touched, setTouched] = useState<Partial<Record<keyof Values, boolean>>>({});
  const [submitted, setSubmitted] = useState(false);
  const [done, setDone] = useState(false);

  const errors = validate(values); // derived, never stored
  const show = (field: keyof Values) => (touched[field] || submitted) && errors[field];

  function update(field: keyof Values, value: string) {
    setValues((v) => ({ ...v, [field]: value }));
  }

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSubmitted(true);
    if (Object.keys(errors).length === 0) setDone(true);
  }

  if (done) return <p>Welcome, {values.email}.</p>;

  return (
    <form noValidate onSubmit={handleSubmit} style={{ display: "grid", gap: 4, maxWidth: 320 }}>
      <label htmlFor={id + "-email"}>Email</label>
      <input
        id={id + "-email"}
        type="email"
        value={values.email}
        onChange={(e) => update("email", e.target.value)}
        onBlur={() => setTouched((t) => ({ ...t, email: true }))}
        aria-invalid={!!show("email")}
        aria-describedby={id + "-email-error"}
      />
      <small id={id + "-email-error"} style={{ color: "#a0461f", minHeight: "1.2em" }}>{show("email") || ""}</small>

      <label htmlFor={id + "-password"}>Password</label>
      <input
        id={id + "-password"}
        type="password"
        value={values.password}
        onChange={(e) => update("password", e.target.value)}
        onBlur={() => setTouched((t) => ({ ...t, password: true }))}
        aria-invalid={!!show("password")}
        aria-describedby={id + "-password-error"}
      />
      <small id={id + "-password-error"} style={{ color: "#a0461f", minHeight: "1.2em" }}>{show("password") || ""}</small>

      <button>Sign up</button>
    </form>
  );
}

This is about as far as hand-rolled validation should go. Past a handful of fields, schema validation with Zod and a form library is less code and fewer bugs, which is URL and form state.

Where forms go next: Actions#

React 19 added a second way to handle forms: pass a function to <form action={fn}>, and React runs it as an async transition with pending state, error handling and automatic reset built in. useActionState, useFormStatus and useOptimistic build on that. They depend on transitions, so they get their own chapter, Actions. Everything in this chapter still applies there: Actions read uncontrolled fields through FormData, and controlled fields still need state.

Pitfalls#

Check your understanding#

Build itAdd a book, two ways

Finish the reading list form. On submit:

  1. If the trimmed title is empty, show Title is required (in the role="alert" paragraph) and add nothing.
  2. Otherwise add the book. If the Add and mark read button submitted the form, the new item reads Title (read); with Add, just Title.
  3. Clear the form after adding.

Keep the form uncontrolled. Press Check.

Reading list: add a book
import { useState, type FormEvent } from "react";

type Item = { title: string; read: boolean };

export default function App() {
  const [items, setItems] = useState<Item[]>([
    { title: "Refactoring", read: true },
    { title: "The Mythical Man-Month", read: false },
  ]);
  const [error, setError] = useState("");

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    // TODO: read the title and the submitter, validate, add, reset
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <label>
          Title <input name="title" />
        </label>{" "}
        <button name="intent" value="add">Add</button>{" "}
        <button name="intent" value="add-read">Add and mark read</button>
        <p role="alert">{error}</p>
      </form>
      <ul>
        {items.map((item, i) => (
          <li key={i}>{item.title + (item.read ? " (read)" : "")}</li>
        ))}
      </ul>
    </>
  );
}
Quick checkPick the model

A search box should filter the visible list on every keystroke. Which input model fits?

Explain it out loudControlled versus uncontrolled

An interviewer asks: "What's the difference between controlled and uncontrolled inputs, and when would you use each?"

Interview angle

Say it in 30 seconds

Every form field has a value that lives in the DOM, so a React form has to decide who owns it. A controlled input renders value from state and updates through onChange, so state is the single source of truth and you can validate, format and drive other UI live. An uncontrolled input uses defaultValue, the DOM owns the value, and you read it with FormData or a ref, usually on submit, with no re-render per keystroke. Handle onSubmit on the form, reset controlled state in onReset, derive validation errors from values, and always validate on the server too.

What's the difference between a controlled and an uncontrolled input?

basic

What causes the warning "A component is changing an uncontrolled input to be controlled"?

intermediate

Is React's onChange the same as the DOM change event?

intermediate

Why doesn't a reset button clear a controlled form, and how do you fix it?

intermediate

How do you approach validation in a React form?

senior

A form has two submit buttons, Save and Publish. How does the submit handler know which was clicked?

senior

Recap#

  • Every input's value lives in the DOM. A controlled input (value plus onChange) makes React state the owner; an uncontrolled one (defaultValue) leaves the DOM in charge until you read it.
  • Use controlled when other UI depends on the value as it changes or you need to shape input; use uncontrolled with FormData for submit-only forms, large forms and files.
  • Handle onSubmit on the form, call preventDefault, use e.currentTarget. Since 19.3 the event carries submitter, and new FormData(form, submitter) includes the clicked button's value.
  • Native reset only restores uncontrolled fields; reset controlled state in onReset (which since 19.3 also fires for React's automatic reset after an Action), or reset everything with a key.
  • Derive validation errors from values, show them after blur or submit, wire them with aria-*, and validate on the server too. Actions come in chapter 25.

Sources#