skip to Main Content

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


  1. The only difference is that when using useRef you store the value returned from watch("password") into the ref and then read it from there, it’s just an extra redundant variable.

    Login or Signup to reply.
  2. 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 of watch, you don’t need those extra rerenders.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search