useForm.ts — Lightweight React forms with TypeScript

Ben Lu
3 min readDec 7, 2020

This covers use-form-ts, the flexible React form library I made to make forms easier to deal with. See my GitHub for more details: https://github.com/ayroblu/use-form-ts

The state of forms with React is wide and varied, but it’s one of the parts of an app that can create the most value while creating the most dread. There are lots of React libraries out there, but writing a form yourself is not a terribly difficult endeavour, should you really constrain yourself to a library?

If you’ve seen this article on which react form library to use in 2020, we can see most of respondents use Formik with the next most common being doing it yourself, then the long tail of solutions. I can see why people might not like solutions like Formik, which add significant structure and restrictions, without necessarily adding a lot benefits.

Why write my own React form library

I haven’t seen a form library I like yet, many examples like Formik force you to use their components rather than using the UI component library that you are using. Others abstract the form building experience which can be great if you’re trying to do what the author wanted to do, but otherwise is inflexible for most needs.

I believed I could make something more expressive that was still simple and low level and easy to understand, but also performed a lot of the data abstractions that other form libraries were doing so that you don’t need to write an onChange handler for each form item for example.

use-form-ts

The useForm hook returns a form object that has a couple methods to help manage forms. State management is up to you, if you want it to be local state, redux, or in context that’s up to you, whichever choice you make is the canonical source of truth for state!

The form object provides a two methods, validate, which is a simple error checker, and createFormItem, this is a curried function that passes through the value, the onChange and onBlur handlers, the name, errorText for errors, and some meta (data), which you can wire up such that the component rendering is value agnostic.

The benefit of this is that you can be a lot more declarative and the data can be fed through to the function in a more data agnostic way.

An example of a more declarative Form can be seen here:

So which design system can I implement it with? All of them! The goal is to not do any abstractions that hide anything from you, what you see in the code is what renders, and there’s just some nice data handling for you.

Next steps

Let me know if this is what you wanted, or if another library already does this better. I didn’t encounter any library that gave me the balance in type safety, data manipulation and transparency that I could write this way, the code can be seen in my GitHub repo here: https://github.com/ayroblu/use-form-ts.

--

--