Skip to main content

Managing Form State

This example addresses how to manage the state of multiple form fields efficiently in React.

A common mistake is to create individual state variables for each form field (e.g., useState for firstName, lastName, email, password).

However, this approach is inefficient and cumbersome, especially for larger forms. Instead, you should use a single object to manage the entire form's state.
By using e.target.name as the key in setForm, you can dynamically update the corresponding field in the state without creating multiple state variables.

This approach keeps the code cleaner and more maintainable.

import { useState } from "react";
import { type } from "@testing-library/user-event/dist/type";

const Four = () => {
// It might seem like you need to use state for each of these fields, but that would be a mistake
// For complex objects, we should use a single object state
// const [firstName, setFirstName] = useState("");
// const [lastName, setLastName] = useState("");
// const [email, setEmail] = useState("");
// const [password, setPassword] = useState("");

const [form, setForm] = useState({
firstName: "",
lastName: "",
email: "",
password: "",
});

const handleForm = (e) => {
setForm({
...form,
[e.target.name]: e.target.value, // this part [e.target.name] will update each specific field based on its name
});
};

return (
<form>
<input
type="text"
onChange={handleForm}
name="firstName"
placeholder="first name"
className="px-4 py-2"
/>

<input
type="text"
onChange={handleForm}
name="lastName"
placeholder="last name"
className="px-4 py-2"
/>

<input
type="email"
onChange={handleForm}
name="email"
placeholder="email"
className="px-4 py-2"
/>

<input
type="text"
onChange={handleForm}
name="password"
placeholder="password"
className="px-4 py-2"
/>
</form>
);
};

export default Four;