I’m making a register form with react-hook-form.
I use useRef to compare "password" and "password_confirm".
I know that useRef is used to variable commonly. and the lecture that I heard let me this way.
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm();
const onSubmit = (data) => console.log(data);
const password = useRef();
password.current = watch("password");
<input
name="password"
type="password"
{...register("password", { required: true, minLength: 6 })}
/>
<input
name="password_confirm"
type="password"
{...register("password_confirm", {
required: true,
validate: (value) => value === password.current,
})}
/>
this way is using useRef for containing current value of "password" input.
so then, password.current validated with value of "password_confirm" input .
however, I think "Why should I use useRef?"
Because, I can make validation in this way.
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm();
const onSubmit = (data) => console.log(data);
<input
name="password"
type="password"
{...register("password", { required: true, minLength: 6 })}
/>
<input
name="password_confirm"
type="password"
{...register("password_confirm", {
required: true,
validate: (value) => value === watch("password"),
})}
/>
I’m curious that the difference between the way using useRef hook and the another way directly using watch function.
2
Answers
The only difference is that when using
useRef
you store the value returned fromwatch("password")
into theref
and then read it from there, it’s just an extra redundant variable.Using
ref
like this might help you to solve some closure problems.But not with the code you provided, here it is not necessary.
Also it is better for your case to use
getValues
instead ofwatch
, you don’t need those extra rerenders.