Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 132 ยท Forms and Actions

Uncontrolled Forms, File Inputs and Complex Forms

Learn uncontrolled React forms with FormData, refs and defaultValue, handle file inputs and previews, build dynamic field arrays with stable keys, and see how form libraries work.

A controlled input stores every keystroke in React state. That is powerful, and also more machinery than many forms need. A contact form with four fields that is only read when the user presses Send does not need to re-render on every letter. The browser already keeps the text in the DOM; you can simply ask for it at submit time. That is an uncontrolled form, and in React 19 it is a first-class, well-supported style.

This lesson covers the three tools of uncontrolled forms (FormData, refs and defaultValue), then the cases that cannot be controlled at all (file inputs), then the hard problems of real forms: dynamic lists of fields and the stable keys they need, and how form libraries such as React Hook Form and Formik are built on these ideas. It assumes you know controlled inputs and form actions.

Reading the whole form with FormData

If every field has a name, new FormData(form) gives you all of them at once. With a form action React hands you the FormData. With an onSubmit handler you build it from the form element: event.currentTarget is the form (use currentTarget, not target, which could be an inner element).

FormData in an onSubmit handler

Press Submit. The first line shows an object with name and a single language ("Python"), while getAll('language') returns ["JavaScript","Python"], both checked values. This is the classic trap: Object.fromEntries keeps only the last value of a repeated name (here Python, the last checked box in the list, hid JavaScript). Whenever a name can repeat (checkbox groups, <select multiple>, field arrays), use getAll.

The advantages of this style: no state per field, no re-render per keystroke, and the code that reads the form is one line. The costs: you cannot react to input while the user types (live character counters, dependent fields), and validation happens at submit or blur time rather than continuously.

defaultValue, defaultChecked and the key trick

Uncontrolled inputs start with defaultValue (or defaultChecked for checkboxes and radios, and defaultValue on a <select>). React uses it only for the first render. If your prop changes later, the field does not follow, because from then on the DOM owns the text. That is the most common surprise: you load a user's profile asynchronously, pass defaultValue={user.name}, and the input stays empty because it was rendered before the data arrived.

The fix is the key prop. Changing a component's key makes React throw away the old element and create a new one, which reads the new default.

defaultValue only counts once; key resets it

Click Load Grace. The "With key" fieldset shows Grace Hopper and New York. The "Without key" fieldset still shows Ada Lovelace and London: the same inputs were kept, and React ignores new defaults on existing inputs. Use key={recordId} on an uncontrolled form (or on the component that holds it) whenever it edits a record that can change. This is the same idea as "resetting state with a key" from Choosing a State Structure.

Refs: reading and controlling a single field

Sometimes you need one field's value or focus without a form. A ref to the DOM node does that: inputRef.current.value reads the current text, inputRef.current.focus() moves the cursor, .select() highlights the text.

Reading an uncontrolled field through a ref

Notice the component does not re-render while you type; it renders only when report changes. Setting .value directly (as clearAndFocus does) is fine for an uncontrolled field, but it is exactly what you must never do to a controlled one. Refs are an escape hatch: prefer FormData for "all the values", and use refs for focus, selection and measuring.

Controlled or uncontrolled?

Choose controlled when... Choose uncontrolled when...
You validate or format on every keystroke You only need the values on submit
One field depends on another (live total, show/hide) The form is simple and independent fields
You need to disable submit until valid You want fewer re-renders in a big form
The value is also shown elsewhere on the page You are wrapping a non-React widget or a file input
You must set values from code (reset, prefill) You can rely on defaultValue, key and form reset

Never switch one input between the two modes. An input that starts with value={undefined} and later gets a string triggers React's "changing an uncontrolled input to be controlled" warning. Initialise controlled state to '', not undefined.

File inputs

A file input is always uncontrolled. Browsers do not let a script set its value (that would let a page choose files from your disk), so React cannot control it. You read event.target.files, a FileList of File objects with a name, size (bytes), type (MIME type, which is the browser's guess from the extension) and lastModified.

To show a preview, create a temporary URL for the file with URL.createObjectURL(file) and use it as an <img src>. These URLs keep the file in memory until you call URL.revokeObjectURL(url), so release them when the preview goes away. An effect with a cleanup function is the right place.

Choosing files, listing them and previewing images

Use Choose files and pick an image and a .txt file from your computer. Each file appears with its type and size, images get a preview, and the first text file is read with file.text(). Our editor runs inside a sandboxed frame, but picking files, FileReader and blob URLs for images all work there. Uploading to a server is not possible from the editor (it has no server), so in a real app the last step looks like this read-only snippet:

JSX
// Read-only: needs a server endpoint. Sending the files is the browser's job:
async function upload(formData) {
  const response = await fetch('/api/upload', { method: 'POST', body: formData });
  if (!response.ok) throw new Error('Upload failed');
}

// <form action={upload}> with <input type="file" name="photos" multiple />
// FormData carries File objects; the browser sets the multipart Content-Type for you.

Never set the Content-Type header yourself when posting FormData: the browser must add the multipart boundary. And validate on the server too: the accept attribute and file.type are only hints, and size limits must be enforced where the file lands.

Always show users what they chose (name, size) before an upload and enforce size limits in the interface, since a 2 GB video picked by accident is a slow way to find out. Check file.size against your limit in the onChange handler.

Dynamic field arrays and stable keys

"Add another phone number" is a field array: the user decides how many inputs exist. Two rules make this work:

  1. Keep the list of rows in state, each with a stable, unique id.
  2. Use that id as the key, never the array index.

The second rule matters most for uncontrolled inputs, whose text lives in the DOM and not in your data. React matches DOM nodes to rows by key. With index keys, removing the first row makes React reuse the first DOM input for what is now the first row, so the text the user typed there stays behind. The demo shows both versions side by side. Type something into the first row of each, then press Remove first in each.

Index keys with uncontrolled rows (pitfall)

Type typed in Alpha into the first row of each box, then remove the first row. In the "wrong" box the remaining labels read Beta and Gamma, but the first input still contains typed in Alpha: the text now sits next to the wrong label. In the "right" box the Alpha row disappears together with its text, because the DOM node belonged to key 1. The same bug affects any state kept inside a row (focus, selection, checkbox state, a child's useState). See Lists and Keys for the full explanation.

A realistic example: a recipe with a list of ingredients

Putting it together: row state with ids, controlled inputs (so we can show a live summary), add and remove buttons, and FormData-free submit because the values are already in state.

Recipe form with a dynamic ingredient list

Add a row, fill it in, remove the first one: the totals update live and the other rows keep their text. When the shape of the data is a list or a tree, controlled state with ids is usually the right call. Use immutable updates (objects and arrays in state) as in updateIngredient.

How form libraries work

Writing the same plumbing in every form (values, errors, touched, submit, async validation) is what form libraries automate. The two best known take opposite sides of this lesson's divide:

  • React Hook Form is built on uncontrolled inputs. You call register('email'), which returns a name, a ref and handlers; the library reads values from the DOM and re-renders only what changed. It is fast on very large forms.
  • Formik (and TanStack Form) keep values in controlled state and give you helpers for onChange, errors and touched fields.

Both integrate with schema validators such as zod. The block below is read-only: these libraries are not installed in our editor, so you would run npm install react-hook-form in your own project.

JSX
// Read-only: needs "npm install react-hook-form".
import { useForm } from 'react-hook-form';

function LoginForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  return (
    <form onSubmit={handleSubmit((values) => console.log(values))}>
      <input {...register('email', { required: 'Email is required' })} />
      {errors.email && <p role="alert">{errors.email.message}</p>}
      <button>Log in</button>
    </form>
  );
}

To understand what such a library does, here is a tiny runnable stand-in that follows the same idea. It does not store values; at submit time it reads them with FormData, runs your rules and reports errors.

A tiny useForm stand-in

Submit an empty form to see both errors, then fill it in. Real libraries add touched and dirty tracking, field arrays, async validation and performance work, but the core is as small as this. Reach for a library when you have many large forms, complex nested data or a team that wants one convention; for a login box, plain React is shorter than the library's import.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use event.currentTarget instead of event.target in new FormData(...)?

    target is the element that was actually clicked or submitted from, which can be a child. currentTarget is the element holding the handler, here the form.
  2. 2. Object.fromEntries(formData) on a form with three checked checkboxes named language gives...?

    Repeated names collapse into one key and the last value wins. Use formData.getAll('language') to get every value.
  3. 3. An uncontrolled input has defaultValue={user.name}, and user changes after the first render. What happens?

    defaultValue is only read when the input is created. A new key makes React create a fresh input that reads the new default.
  4. 4. Why can a file input not be controlled?

    Setting the value of a file input would let a page pick files from the user's disk, so browsers forbid it. You read event.target.files instead.
  5. 5. What is the main danger of using the array index as the key of rows that contain uncontrolled inputs?

    React reuses DOM nodes by key. With index keys, removing the first row reuses the first input for the next row, so its typed text ends up next to the wrong label.

Summary

  • Uncontrolled forms read values when needed: new FormData(event.currentTarget) for all fields, refs for single fields, defaultValue/defaultChecked for initial values.
  • Object.fromEntries loses repeated names; use getAll for checkbox groups and multiple selects.
  • defaultValue only matters on the first render; change the component's key to load a different record.
  • Never mix modes in one input: start controlled state at '', not undefined.
  • File inputs are always uncontrolled: read event.target.files, preview with URL.createObjectURL, revoke the URL in an effect cleanup, and validate size and type on the server too.
  • Field arrays need state with stable ids and key={row.id}, never the index.
  • React Hook Form is uncontrolled and fast; Formik is controlled. Both are conveniences over the same primitives, and a form library is optional.

Next: Fetching Data