Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 2

Controlled, Uncontrolled and FormData

Decide where a field's value lives — React state or the DOM — and read any form back with FormData at submit time.

Contentsand lesson path

What you will learn

  • Handle submission in React with controlled or uncontrolled inputs and form actions (useActionState, useFormStatus), including pending state, double-submit prevention and server-returned errors, treating server-side validation as mandatory.

Prerequisites: React Components & State

01. Why it matters

A form field can hold its value in two places at once: in the DOM element itself, and in React state that re-renders the element on every change. A controlled input is one whose displayed value comes from state: value={x} with an onChange that writes back. An uncontrolled input is one the DOM keeps by itself; React renders it once with a defaultValue (or nothing) and reads the value later. Neither is the correct answer in general — the question is which component owns the value for this field.

Choosing well keeps forms small. Validation that must react to every keystroke, fields that format themselves, and buttons enabled by a cross-field rule all want state. A field the user simply fills in and leaves alone does not: the DOM already stores the text perfectly well, and re-rendering the whole form on each keystroke buys nothing. At submit time both kinds meet in the same place — the form element, whose values FormData reads whatever owns them. This lesson builds the judgement and the reading pattern; the next one hands the form to a React action.

02. Controlled: state is the single source of truth

With value and onChange, React state decides what the field shows, and every keystroke goes in a circle: the DOM reports the event, your handler updates state, React re-renders with the new value. That circle is the point. The rendered output below the field — a preview, a live character count, an inline rule such as "we need at least one guest" — updates with the same keystroke, because it renders from the same state.

TypeScript · controlled-form.test.tsx, the form under test
import { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { expect, it } from 'vitest';

function BookingForm({
  onSubmit,
}: {
  onSubmit: (data: Record<string, string>) => void;
}) {
  const [guests, setGuests] = useState(2);
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const data = Object.fromEntries(new FormData(event.currentTarget));
        onSubmit(data as Record<string, string>);
      }}
    >
      <label htmlFor="guests">Guests</label>
      <input
        id="guests"
        name="guests"
        type="number"
        min="1"
        max="6"
        value={guests}
        onChange={(event) => setGuests(Number(event.target.value))}
      />
      <p>{`Preview: ${guests} ${guests === 1 ? 'guest' : 'guests'}`}</p>

      <label htmlFor="notes">Notes</label>
      <textarea id="notes" name="notes" defaultValue="Near the window" />

      <button type="submit">Book</button>
    </form>
  );
}

The form mixes both styles on purpose. guests is controlled, so the preview can live next to it. notes is uncontrolled: it starts at "Near the window" through defaultValue and nobody needs to hear about it until submit. The submit handler reads the whole form with new FormData(event.currentTarget), which collects every named control straight from the DOM — controlled and uncontrolled alike. The tests below drive the form with Testing Library and print what happens; they sit in the same file and run with the Vitest and jsdom setup from the lab.

TypeScript · the tests (Vitest 5.1.2, Testing Library 16.3.3, jsdom 31.0.1)
it('re-renders the preview on every keystroke of a controlled field', () => {
  render(<BookingForm onSubmit={() => {}} />);
  fireEvent.change(screen.getByLabelText('Guests'), { target: { value: '4' } });
  expect(screen.getByText('Preview: 4 guests')).toBeTruthy();
  console.log('controlled: preview now shows -> "Preview: 4 guests"');
});

it('reads both fields from FormData on submit', () => {
  let received: Record<string, string> = {};
  render(<BookingForm onSubmit={(data) => (received = data)} />);
  fireEvent.change(screen.getByLabelText('Guests'), { target: { value: '4' } });
  fireEvent.change(screen.getByLabelText('Notes'),
    { target: { value: 'Ground floor' } });
  fireEvent.click(screen.getByRole('button', { name: 'Book' }));
  console.log('on submit, FormData holds ->', JSON.stringify(received));
  expect(received).toEqual({ guests: '4', notes: 'Ground floor' });
});
Expected output (npx vitest run, console lines only)
controlled: preview now shows -> "Preview: 4 guests"
on submit, FormData holds -> {"guests":"4","notes":"Ground floor"}

The second assertion is the quiet one worth noticing: notes was never in state, yet FormData delivers "Ground floor". That is the division of labour — state for what React must re-render, the DOM for what it need not. One warning about the controlled half: value without an onChange is not an uncontrolled input. React sees a value it is told to render and no way to change it, so typing does nothing and the field is effectively read-only.

03. FormData: the DOM speaks at submit time

FormData is a small map from names to values, built from every control that has a name. Passing the form element — new FormData(formEl) — collects textareas, selects, checkboxes (only when ticked, submitted as on unless you give them a value) and hidden inputs. It is iterable, and three reads cover almost everything: get(name) for the first value, getAll(name) for repeated names such as checkbox groups, and iteration or Object.fromEntries for the lot. The same interface exists in Node, which makes the API easy to explore in isolation.

JavaScript · formdata-demo.mjs (Node 22.23.2)
// FormData exists in browsers and in Node; the API is the same.
const fd = new FormData();
fd.set('email', '[email protected]');
fd.set('guests', '2');
fd.set('guests', '3'); // set() replaces, append() adds a second value
fd.append('tag', 'window');
fd.append('tag', 'quiet');

console.log('get("guests")     ->', fd.get('guests'));
console.log('getAll("tag")     ->', fd.getAll('tag'));
console.log('has("name")       ->', fd.has('name'));
console.log('entries:');
for (const [key, value] of fd.entries()) console.log(`  ${key}=${value}`);
console.log('new URLSearchParams(fd).toString()');
console.log('  ->', new URLSearchParams(fd).toString());
console.log('Object.fromEntries(fd)');
console.log('  ->', JSON.stringify(Object.fromEntries(fd)));
Expected output
get("guests")     -> 3
getAll("tag")     -> [ 'window', 'quiet' ]
has("name")       -> false
entries:
  [email protected]
  guests=3
  tag=window
  tag=quiet
new URLSearchParams(fd).toString()
  -> email=rin%40example.com&guests=3&tag=window&tag=quiet
Object.fromEntries(fd)
  -> {"email":"[email protected]","guests":"3","tag":"quiet"}

Two details from the output catch people out. set replaced the old guests value while append kept both tags, which is exactly how a form submits repeated names — so prefer getAll for anything the user can tick twice. And Object.fromEntries keeps only the last value per name, because object keys are unique; convenient for single-value forms, silently lossy for the rest. URLSearchParams shows the shape the values take on a plain POST: same names, percent-encoded.

04. Choosing, and one boundary

A workable default: uncontrolled unless the interface must react to the value. Reach for a controlled input when a preview or counter must update per keystroke, when validation should appear while typing, when one field's value constrains another, or when a submit button must stay disabled until a rule passes. Reach for uncontrolled when the value is written once and read at submit — and always for <input type="file">, whose contents JavaScript may only read through the FileList the browser hands you; you cannot set its value from state at all. Large forms with many rules often outgrow hand-rolling both styles; libraries such as React Hook Form keep fields uncontrolled under the hood and register them into a schema-driven validation loop, which is the same division of labour at a larger scale.

The choice also decides how the form is tested. A controlled field is asserted through what renders — type into it, then expect the preview text. An uncontrolled field is asserted through the DOM or the submitted payload, which is why the tests above read received rather than an input's value. Mixed forms need both, and FormData is the meeting point: submit once and assert on the whole payload, regardless of which style each field uses.

05. Check your understanding

Practice check · 3 questions

Where should the value live?

Three fields from a real product.

Q1. A comment box must show "123 characters left" under the field while the user types. How should the field be wired?
Q2. A teammate writes <input value={draft} /> and forgets the onChange handler. What happens when the user types?
Q3. A form has two ticked checkboxes, both named tag with values window and quiet. What does new FormData(form) return for tag?
Practice only: not graded, not saved, not evidence.

06. Apply it

Take a form from your own project and classify every field: controlled, uncontrolled, or undecided. For each controlled field, name the thing that re-renders because of it — if nothing does, switch it to uncontrolled and read it from FormData. For the submit handler, print Object.fromEntries(new FormData(form)) and check that every field you expected is there, then add a checkbox group and confirm getAll returns every ticked value. Notice how much state the form no longer needs.

07. Review prompt

Without looking back: what makes an input controlled, and what circle does every keystroke travel? What does defaultValue render, and when is the value read? Which two reads on FormData handle single and repeated names, and what does Object.fromEntries quietly drop? Which input type can never be controlled, and why?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check