Controlled Components in React: Forms Tutorial with Examples
Learn the state, value and onChange loop by building a name preview and a complete course-interest form with exact validation outcomes.
KnowledgeGate Team
Exam prep & CS education

An <input> can render yet freeze, reset or diverge from state. Build a controlled input, a course-interest form, exact validation outcomes, repairs and exercises. For a structured path, use the React and Redux course.
1. What makes a React form control controlled
State holds a controlled input's value, value or checked displays it, onChange updates state, and React renders again. The official React input reference requires this update to be synchronous.
Start with name = ''. Type A: event.target.value is 'A', setName('A') schedules an update, and the next render supplies value="A". Finish typing, and state and input contain 'Asha'. State is the source of truth.
value controls every render; defaultValue="Asha" only sets an uncontrolled input initially. Apply this across coding and skill-development paths.

2. Build the smallest runnable controlled input
import { useState } from 'react';
export default function NamePreview() {
const [name, setName] = useState('');
return (
<section>
<label htmlFor="name">Name</label>
<input
id="name"
value={name}
onChange={event => setName(event.target.value)}
/>
<p>Hello, {name || 'learner'}!</p>
</section>
);
}Initially, useState('') supplies a string and shows Hello, learner!. Type Asha: state is 'Asha' and the paragraph says Hello, Asha!. Delete four characters, and '' restores Hello, learner!.
The handler copies the DOM value into state. With only <input value={name} />, typing cannot change the display. Two-way binding still has explicit event and render steps.
3. Control a complete form with one state object
import { useState } from 'react';
const initialForm = {
fullName: '', email: '', track: 'react', notes: '', agree: false
};
export default function CourseInterestForm() {
const [form, setForm] = useState(initialForm);
function handleChange(event) {
const { name, type, value, checked } = event.target;
setForm(previous => ({
...previous,
[name]: type === 'checkbox' ? checked : value
}));
}
return (
<form>
<input name="fullName" value={form.fullName} onChange={handleChange} />
<input name="email" type="email" value={form.email} onChange={handleChange} />
<select name="track" value={form.track} onChange={handleChange}>
<option value="react">React</option>
<option value="javascript">JavaScript</option>
</select>
<textarea name="notes" value={form.notes} onChange={handleChange} />
<label>
<input name="agree" type="checkbox" checked={form.agree} onChange={handleChange} />
I agree to submit this form
</label>
<pre>{JSON.stringify(form, null, 2)}</pre>
</form>
);
}Enter Asha Jain, asha@example.com and Build a quiz app, keep track as react, and tick the box. The rendered JSON is { "fullName": "Asha Jain", "email": "asha@example.com", "track": "react", "notes": "Build a quiz app", "agree": true }.
The functional updater reads current state; the spread keeps siblings. Returning only { [name]: value } for email loses four keys. Review HTML form elements and attributes if needed.
React puts a controlled select value on <select>, not its option. A controlled textarea uses value, not child text.
4. Handle checkboxes, radio buttons and numeric inputs deliberately
For a checkbox, event.target.value is commonly 'on'; event.target.checked is boolean. React controls checkboxes and radios through checked. Ticking agree must store true.
const [plan, setPlan] = useState({
mode: 'self-paced', hoursPerWeek: '6', emailUpdates: false
});
function handlePlanChange(event) {
const { name, type, value, checked } = event.target;
setPlan(previous => ({
...previous,
[name]: type === 'checkbox' ? checked : value
}));
}
<input type="radio" name="mode" value="self-paced"
checked={plan.mode === 'self-paced'} onChange={handlePlanChange} />
<input type="radio" name="mode" value="guided"
checked={plan.mode === 'guided'} onChange={handlePlanChange} />
<input type="number" name="hoursPerWeek"
value={plan.hoursPerWeek} onChange={handlePlanChange} />
<input type="checkbox" name="emailUpdates"
checked={plan.emailUpdates} onChange={handlePlanChange} />Choose guided, replace 6 with 8, and tick updates. State is { mode: 'guided', hoursPerWeek: '8', emailUpdates: true }. Number inputs report strings. Preserve '', reject blanks, then convert. Number('8') is 8; Number('') is 0 and could create false data.
5. Validate and submit the exact form state
Add errors state, then validate before creating a result:
const [errors, setErrors] = useState({});
function validate(values) {
const next = {};
if (values.fullName.trim().length < 3)
next.fullName = 'Enter at least 3 characters';
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email))
next.email = 'Enter a valid email';
if (values.agree !== true)
next.agree = 'You must agree before submitting';
return next;
}
function handleSubmit(event) {
event.preventDefault();
const nextErrors = validate(form);
setErrors(nextErrors);
if (Object.keys(nextErrors).length > 0) return;
const payload = { ...form };
console.log(payload);
}Wire it through <form onSubmit={handleSubmit}>, show errors.fullName, errors.email and errors.agree beside their controls, and use <button type="submit">Submit</button>.
For { fullName: ' AJ ', email: 'asha.example.com', track: 'react', notes: '', agree: false }, trimming gives AJ, length 2. Errors are { fullName: 'Enter at least 3 characters', email: 'Enter a valid email', agree: 'You must agree before submitting' }. preventDefault() stops navigation; no payload is produced.
Correct to { fullName: 'Asha Jain', email: 'asha@example.com', track: 'react', notes: 'Build a quiz app', agree: true }. Zero errors produce that payload. Logging is client-side only. Study Mongoose schemas, models, validation and population before persistence.

6. Keep one owner for each input from the first render
Live validation, conditional UI and shared values need the current value in React state, so every field in CourseInterestForm stays controlled. React Forms: Controlled vs Uncontrolled Components compares state ownership, shows a ref-based uncontrolled example and covers the interview angle; the course-interest form here instead traces multiple fields, exact submit results and validation.
With useState(), undefined makes email uncontrolled; setting 'asha@example.com' then controls it. Use useState('') and keep a string, following React's no-switch and non-null guidance.
7. Diagnose the common controlled-form failures
Failure | Outcome | Repair |
|---|---|---|
|
| Add state and synchronous |
| Mutates and reuses one object | Use |
| Keeps only | Spread previous state first |
| Stores | Read |
Form button has no | Reset or Preview may submit | Use |
React requires synchronous updates. Delaying setName(nextValue) by 100 milliseconds, or substituting another string in that callback, can revert the field and move the caret.
Check the initial type, handler, value or checked, then other keys.
8. Exercises, the short version and the next study action
Try these before reading the answers:
Start
cityat'Jaipur', control one text input, then typePune.Add
beginnerandintermediateradios to{ level: 'beginner' }, then select the second.Validate
hoursPerWeekfor''and'6'.
Input and state both contain
'Pune';{city}rendersPune.State is
{ level: 'intermediate' }; only that radio haschecked={true}.For
'', showEnter weekly hoursand do not callNumber. For'6', validation passes and the payload stores the number6.
Keep this six-line recall card:
Initialise controlled values with the correct type.
Render
valueorchecked.Update from
onChange.Preserve sibling fields in object state.
Validate before producing a payload.
Never switch a field between controlled and uncontrolled.
Continue through the Web Development pillar. Type NamePreview, rebuild CourseInterestForm from memory, and submit the exact Asha Jain payload. Use the course above for React, or the MERN Stack full-stack development course for full-stack projects.
Keep learning
React Forms: Controlled vs Uncontrolled Components, Validation and the Interview Questions
Follow the value through a state-driven form and a ref-driven form, then choose the right model for live validation, simple inputs and file uploads.
React Controlled Components: Interview Questions and Coding Problems
Trace a five-field React form, build one safe change handler, and debug the controlled-input mistakes that commonly appear in interviews and coding rounds.
React Events Tutorial: onClick, Forms and Runnable Examples
Build one PracticeTracker component, follow every click, change and submit, then learn exactly when to use preventDefault and stopPropagation.
Testing React Components: A Runnable Vitest and Testing Library Tutorial
Build and test a small React progress component from its initial render through completion. The examples use accessible queries, awaited actions, and an exact mock assertion.





