DEV Community

Jovi De Croock
Jovi De Croock

Posted on • Updated on

Hooked-Form

A short introduction, hey my name is Jovi I am a web and mobile Engineer in a Belgian company and this is my first dev.to post, in light of the upcoming React-hooks release I decided to give it a shot.

The first time I heard about hooks, I quickly realized this would be a good way of reducing the bundle size needed for specific libraries as well as improve the overall readability of code.
Classes imply an overhead when they are transpiled down and at this point in time, library authors always transpile the library down for almost all browsers to be supported. In essence we could move away from this but that's a discussion for another time.

That's why I felt the need to make two libraries one toolbelt with hooks and a form library.

The form library will be the only one talked about in this post, it follows the Form/Field method. This method is used by popular libraries like redux-form.

I'm quite happy with the result since it ended up being a 2.8KB minified gzipped bundle, this is significantly less than other popular variants.

Hooks

The library exposes a set of hooks:

  • useField
  • useError
  • useFieldArray

These hooks can be used in your components to construct components, these will automatically fetch the methods, values and meta information when passed a fieldId.

Components

The library also exposes a set of Components, one might ask why was this choice made when we already have the hooks to make these ourselves.

Well with the components I opted to make a more optimised version, these memoize the component they have to render and only recalculate upon changes in their value, error, ...

So for every hook there's a component:

  • Field
  • Error
  • FieldArray

But there's one more and that is the Form component. I opted to keep the container as a HOC since a lot of hooks are used in it to preform validation,...

Example

I made a small example in a codesandbox of a basic working form: https://codesandbox.io/s/k8mylo9lo

This example showcases the basic usage of a Field and a FieldArray. The fun thing about hooks is that when you want to override the existing Field implementation you are free to do so just by grabbing useField. It will return the values/methods for the field you are passing and you can implement it yourself.

Concluding

I use hooked-form actively in one of my side-projects and I'm really happy about how it's turning out.

You can always read more in the documentation

I hope you've enjoyed the post and feedback about it is always welcome!

If you want to learn more about forms and the reasoning behind my choices you can read more here:

Field-Form method
Hooked-Form choices

Top comments (0)