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

3

u/svish Dec 17 '23

Actually, for forms superRefine it really terrible.

First of all, you get your validation very awkwardly cut in half, or worse. If B depends on A, you can only validate B partially, for example having to keep it optional even if its required when A is true. Even worse when there's a series of dependencies.

Second, and worst of all, zod doesn't even touch the refinements until the whole "base object" is valid. This is fine in most cases, but for forms this means the user doesn't get certain error messages until they've gone through the whole form. Get to the end, and suddenly a whole new "layer" of errors pop up.

For forms, Zod is just awful in every way that matters the most.

1

u/ashenzo Dec 18 '23 edited Dec 18 '23

If you define the fields that relate to each other in their own schema and refine the validation there, then intersect them with another schema containing the rest of the form, the refine checks will run on the first validation pass with the rest of it. This is super hacky and annoying but it does work.

Note: you can only intersect 2 schemas at a time for this to work, but you can intersect more than two schemas multiple times (2 each intersection).

2

u/svish Dec 18 '23

Do you realize how many steps and complicated words you just used? That is not just "hacky", it's awful :p

yup.number().when(
  ['x', 'y'],
  ([x, y], schema) => x === true && typeof y === 'number'
    ? schema.required().max(y)
    : schema
)

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)