
In this article, we will explore how to use the react-hook-form library in detail. It's the most popular React library for creating forms compared to formik, react final form, and others, and I use it for all my client projects. So instead of manually writing all of the code and handling complex forms with validation logic, we can use the most popular React library for this, react-hook-form. But as your form gets more complex and you need to add various validations, it becomes a complicated task. It involves handling all the input states and their changes and validating that input when the form gets submitted.įor simple forms, things are generally manageable. There are also other design decisions why I did not make Formik clone, but that's for another blog post.This content originally appeared on DEV Community 👩💻👨💻 and was authored by Yogesh ChavanĬreating forms in React is a complex task.

Once we use io-ts, for the reasons I mentioned, we can not use Formik, and honestly, that hook is so simple yet powerful, that we don't have to. I recommend you try both examples.Īs for useForm. Hopefully, soon you realize that plain string or number types are close to any. Email and Verified email (both strings) with type safety. For example, string which is only the email, not any string, or an array with the first item of type A and second optional type B. It's about F#, but with io-ts, we can model a much stricter schema in a similar way. But thank you for a comment, I should highlight it.Īnyway, please check the first five minutes of this talk /watch?v=PLFl95c-IiU to understand my motivation.

Yup does not support branded types nor option nor any other fp-ts types. So far we have seen a domain model that can be validated in any context, but how to make a form from that? We made a little yet powerful React Hook for that.ĭon't get me wrong, I know both Formik and Yup. If some email is Email, we can check whether it's also unique on the server, and if not, we can show error "This email is already used." The beauty of this approach is endless scalability and perfect type correctness from day 0. We use the Option monad.Įvery branded type has a string name, which we can use for validation error messages. We need to tell "This type is an optional type of another type.". Traditionally, we would use a null or undefined or empty string, which is a very suboptimal and not generic approach. Note option(Phone), the option is a generic type. And String64 is the intersection of NonEmptyTrimmedString and Ma圆4String. Import ) Įmail type itself is the intersection of String64 and EmailString.
