Using FormData API with Uncontrolled Forms
What you'll learn: How to extract all form values at once using the native FormData API, eliminating the need for individual refs for each input.
The Problem with Multiple Refs
In the previous lesson, you accessed multiple refs on submit—one useRef for each input. This works, but gets repetitive:
const nameRef = useRef(null);
const emailRef = useRef(null);
const ageRef = useRef(null);
// ... dozens more for larger forms
The FormData Solution
The native browser FormData constructor can extract all input values from a form at once, as long as each input has a name attribute:
function MyForm() {
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const name = formData.get('username');
const email = formData.get('email');
console.log({ name, email });
};
return (
<form onSubmit={handleSubmit}>
<input name="username" defaultValue="" />
<input name="email" defaultValue="" />
<button type="submit">Submit</button>
</form>
);
}
Key differences:
- No refs needed
event.targetis the form element itselfFormDatareads thenameattribute of each inputformData.get('fieldName')retrieves the value
Converting to an Object
You can convert all form data to a plain object:
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
// { username: '...', email: '...' }
Key Takeaway: The FormData API lets you extract all uncontrolled form values in one line without managing individual refs, as long as your inputs have name attributes—perfect for simple, submit-only forms.