Introduction
When writing forms in React, many people initially combine useState and onChange to manage input values.
However, using React Hook Forms actually makes these unnecessary.
Here, we'll explain why useState is unnecessary and the role of handleSubmit / onSubmit.
Problem
Common form syntax:
const [userId, setUserId] = useState("");
<input value={userId} onChange={(e) => setUserId(e.target.value)} />
- Input management using useState and onChange is time-consuming.
Solution
In RHF, register already manages input values.
Therefore, useState and onChange are unnecessary.
const onSubmit = (data: any) => {
navigate(`/cards/${data.userId}`);
};
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("userId")} placeholder="Enter ID" />
<button type="submit">Submit</button>
</form>
Key Points
register("userId") → React Hook Form automatically manages state.
handleSubmit(onSubmit) → Collects input values and passes them to data.
onSubmit → Processing upon submission (in this case, navigate to the next page).
This neatly unifies "input management" and "submission processing"!
Top comments (0)