HTML form elements such as <input>, <textarea>, and <select> naturally maintain their own internal state in the browser DOM. In React, the recommended pattern is to make React state the "single source of truth". An input whose value is controlled by React is called a Controlled Component.
Figure 5: Controlled Components (React state driven) vs Uncontrolled Components (Direct DOM refs).
Rather than creating 10 individual useState variables and 10 separate handler functions for a registration form, combine form fields into a single state object and use the input's name attribute:
import React, { useState } from 'react';
function StudentRegistrationForm() {
const [formData, setFormData] = useState({
fullName: '',
email: '',
course: 'BCA',
agreeTerms: false
});
const [formError, setFormError] = useState('');
// Single Generic Input Change Handler
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData(prev => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
if (!formData.fullName.trim()) {
setFormError('Full name is required!');
return;
}
setFormError('');
console.log('Submitted Data to Backend:', formData);
alert(`Registration successful for ${formData.fullName}!`);
};
return (
<form onSubmit={handleSubmit} className="form-card">
<h3>BCA Student Registration</h3>
{formError && <p style={{ color: 'red' }}>{formError}</p>}
<div>
<label>Full Name:</label><br />
<input
type="text"
name="fullName"
value={formData.fullName}
onChange={handleChange}
/>
</div>
<div>
<label>Email Address:</label><br />
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</div>
<div>
<label>Course Selection:</label><br />
<select name="course" value={formData.course} onChange={handleChange}>
<option value="BCA">BCA</option>
<option value="B.Tech">B.Tech CS</option>
<option value="MCA">MCA</option>
</select>
</div>
<div>
<label>
<input
type="checkbox"
name="agreeTerms"
checked={formData.agreeTerms}
onChange={handleChange}
/>
I accept the college guidelines
</label>
</div>
<button type="submit" disabled={!formData.agreeTerms}>
Register Student
</button>
</form>
);
}
export default StudentRegistrationForm;
Now let us examine the alternative form pattern using direct DOM references in React Uncontrolled Components & useRef.
Accelerate your React mastery by studying these tightly connected core tutorials:
Comparing controlled inputs with DOM refs.
Modern async form actions with useActionState.
Preventing XSS injection in user inputs.