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/sauland Dec 18 '23 edited Dec 18 '23

You can do conditional validation pretty easily by utilizing the setKey function of zod schemas. Like this:

// type safe implementation of setKey
const zodSetKey = <
  Schema extends z.ZodObject<any>,
  Shape extends Schema['shape'],
  Key extends keyof Shape,
>(
  schema: Schema,
  key: Key,
  newSchema: (shape: Shape[Key]) => z.ZodType<z.infer<Shape[Key]>>,
): Schema => {
  return schema.setKey(key as string, newSchema(schema.shape[key])) as Schema;
};

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

const SignUpForm = () => {
  const form = useForm<SignUpFormValues>({
    resolver: (values, ctx, resolverOptions) => {
      let schema = SignUpFormValues;
  
      if (values.password && values.confirmPassword) {
        schema = zodSetKey(schema, 'confirmPassword', (s) =>
          s.refine(() => values.password === values.confirmPassword, 'Passwords do not match'),
        );
      }
  
      return zodResolver(schema)(values, ctx, resolverOptions);
    },
  });

  return (
    ...
  )
}

3

u/svish Dec 18 '23

You have a very different definition of "pretty easy" than I do

1

u/sauland Dec 18 '23

Lol, idk what to tell you if you think that's difficult. A small utility function that you can use across your entire codebase for type-safe conditional validation in your forms is indeed pretty easy. Definitely easier than migrating all your validation to yup to use its messy untyped when logic.

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.

→ More replies (0)