1. Controlled vs Uncontrolled Components
- Uncontrolled: Form inputs manage their own state internally in the DOM. You pull values using a
ref. - Controlled (Recommended): React state is the single source of truth. Every keystroke updates React state, and the input value is bound directly to that state variable.
2. Single Input Controlled Component
import { useState } from 'react';
function SearchBar({ onSearch }) {
const [query, setQuery] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
onSearch(query);
};
return (
);
}
3. Managing Multi-Field Forms Elegantly
Instead of creating a separate useState for every input, manage all fields inside a single state object using dynamic object keys [e.target.name]:
function StudentRegistration() {
const [formData, setFormData] = useState({
fullName: "",
email: "",
examCategory: "NEET",
agreedToTerms: false
});
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData(prev => ({
...prev,
[name]: type === "checkbox" ? checked : value
}));
};
const handleRegister = (e) => {
e.preventDefault();
console.log("Submitting payload:", formData);
};
return (
);
}