Skip to main content
Albero Academy

Forms & Controlled Components

Handle real forms — controlled inputs, one handler for many fields, validation and submission, plus when to reach for a form library.

Chapter 6React16 min readBeginner friendly
  • #React
  • #Forms
  • #Validation

Forms are where most apps collect input, and React's model — state is the single source of truth — is worth getting right. This chapter goes beyond Chapter 4's intro to managing many fields, validating, submitting, and knowing when a form library earns its keep.

Controlled inputs

A controlled input's value comes from state and onChange writes back to it — so the value is always available in your code:

a controlled input
const [email, setEmail] = useState("");
<input value={email} onChange={e => setEmail(e.target.value)} type="email" />

One handler, many fields

Store the whole form in one state object and use the input's name to update the right field:

scalable form state
const [form, setForm] = useState({ name: "", email: "", programme: "" });
const handleChange = (e) => {
const { name, value } = e.target;
setForm(prev => ({ ...prev, [name]: value })); // spread + computed key
};
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />

Submitting

handle submit
const handleSubmit = async (e) => {
e.preventDefault(); // stop the page reload
await fetch("/api/enquiry", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
};
<form onSubmit={handleSubmit}> … <button>Send</button> </form>

Validation

errors in state
const [errors, setErrors] = useState({});
const validate = () => {
const e = {};
if (!form.email.includes("@")) e.email = "Enter a valid email";
if (form.name.length < 2) e.name = "Name is too short";
setErrors(e);
return Object.keys(e).length === 0; // true if no errors
};
{errors.email && <p className="error">{errors.email}</p>}

When to use a library

Hand-rolled state is fine for small forms. For large forms with complex validation, a library like React Hook Form removes boilerplate and improves performance (it minimises re-renders). Reach for one when the manual approach starts to hurt — not before.

Practice

Build a "Book a call" form with four fields in a single state object updated by one handleChange. Add a validate that populates an errors object and shows messages, and an onSubmit that only posts when valid.

Key takeaways

  1. 01Controlled inputs bind value to state and write back on onChange — state is the source of truth.
  2. 02Store many fields in one object; update with { ...prev, [name]: value } using the input's name.
  3. 03On submit, call e.preventDefault() then send the form state.
  4. 04Keep validation errors in state and render messages conditionally.
  5. 05Hand-roll small forms; reach for React Hook Form when complexity/performance demands it.