r/reactjs • • Dec 17 '23

Discussion Is react hook form overhyped?

I created a custom form validation hook.Its a simple hook and I felt I didn't needed react hook forms for just simple form validation. For simpe validation writing that much code and loading the whole library felt not right. Maybe I am wrong.

0 Upvotes

45 comments sorted by

View all comments

Show parent comments

1

u/svish Dec 18 '23

But you're also manually setting up a custom resolver for every form, adjusting the schema manually, and like with superRefine splitting up the validation into separate pieces in different places.

With Yup the whole definition of what a valid form submission is can be stored in a single place, and with our form wrapper component we don't even need to setup the resolver at all, because we just pass that single definition as a schema prop.

Also, we didn't migrate all our validation logic. Our API validation, config, and local storage validation still uses zod. So all we migrated were the 2-3 out of several large forms we had done with zod before realising it was terrible and switching over to Yup for those.

1

u/sauland Dec 18 '23

In a real world app the resolver setup logic would be abstracted away into a custom useForm hook, so you wouldn't have to write the full thing every time.

Yes, you can't define the conditional validations directly in the schema, but that shouldn't really be a problem since form schemas are tightly coupled to the form component anyways, so usually you would rather want to reuse the component itself than just the schema.

A real life implementation would look something like this, which IMO is pretty straightforward and doesn't require the installation of 2 separate validation libraries:

const SignUpFormValues = z.object({
  email: z.string().email(),
  password: z.string(),
  confirmPassword: z.string(),
});
type SignUpFormValues = z.infer<typeof SignUpFormValues>;

const SignUpFormResolver = (t: TFunction) => (values: SignUpFormValues) => {
  let schema = SignUpFormValues;

  if (values.password && values.confirmPassword) {
    schema = zodSetKey(schema, 'confirmPassword', (s) =>
      s.refine(
        () => values.password === values.confirmPassword,
        t('signUp.confirmPassword.passwordsDontMatch'),
      ),
    );
  }

  return schema;
};

const SignUpForm = () => {
  const { t } = useTranslation();

  const form = useForm<SignUpFormValues>({
    resolver: SignUpFormResolver(t),
  });

  return (
    <Form form={form}>
      <TextInput name={form.names.email} label="Email" />
      <TextInput name={form.names.password} type="password" label="Password" />
      <TextInput name={form.names.confirmPassword} type="password" label="Confirm password" />
    </Form>
  );
};