Watch one field at a time
Register both controls, read the field that drives the dependency with useWatch, and call setValue when the dependent field should be reset. Start mismatched fields with explicit defaults.
Clear a value when its field becomes irrelevant
Use this in a client component. The phone field is meaningful only when the visitor asks for a call.
JSX
import { useEffect } from "react";
import { useForm, useWatch } from "react-hook-form";
export default function ContactPreferences({ onSubmit }) {
const { control, handleSubmit, register, setValue } = useForm({
defaultValues: { email: "", replyBy: "email", phone: "" },
});
const replyBy = useWatch({ control, name: "replyBy" });
useEffect(() => {
if (replyBy !== "phone") {
setValue("phone", "", { shouldValidate: true });
}
}, [replyBy, setValue]);
return <form onSubmit={handleSubmit(onSubmit)}>
<label>Email <input type="email" {...register("email", { required: true })} /></label>
<label>Reply by
<select {...register("replyBy")}>
<option value="email">Email</option>
<option value="phone">Phone call</option>
</select>
</label>
{replyBy === "phone" && <label>Phone
<input type="tel" {...register("phone", { required: true })} />
</label>}
<button>Send message</button>
</form>;
}Test changing the choice
Complete the phone field, switch to email, and inspect the values passed to your submit handler. Validate the conditional rules where you process requests as well.