Simplifying React Forms with Hooks

Forms, like death and taxes, are one of the unavoidable aspects of web development. From Login Forms, Contact Pages, to heavy form-centric applications - at some point, you will need to wire up an input field to your application state. Working with forms in React can require a bit of boilerplate, and while there are libraries like Formik, Redux Form or React Redux Form can help make things easier, they can be overkill for many situations.

React Hooks were announced at React Conf 2018, and are on the roadmap for release in early 2019. Hooks provide a way to handle stateful logic in functional components, while also providing a way to share non-UI logic and behaviour across your application. To better understand this, and see it in action, I will be walking you through how to leverage the useState hook for simplifying a controlled component, and then creating a custom hook to simplify input handling even more.

Controlling Inputs The Old Way

First, let's start with an example from the React Docs on Forms, and create a controlled component:

This is a good start and has already cleaned up handling an input. We don't need to create an instance of the React component class, worry about the context of this and we can start to get the benefits of functional components while still being able to do stateful logic.

We are not limited to the hooks that React provides, but can also build your own hooks, and this is where the value of hooks starts to shine for me:

The ability to have reusable logic shared across components, without having to introduce extra components into our hierarchy.

There are many patterns out there that can accomplish this such as Higher Order Components, Render Props, etc. These patterns are still useful, however, if you have a HoC, or component using render-props that has no UI to it and is only rendering a single child - a hook might be a better way of handling this.

Creating Custom Hooks

To see what this looks like, I will create a useInput hook to simplify handling inputs even further.

With hooks on the React Roadmap to land in Q1 of 2019, I'm excited to see how the leveraging them can start cleaning up and simplifying the code I am working on today. If you're interested in learning more about how to start applying it in your own code, stayed tuned for my upcoming post on how to refactor your existing components to leverage the power of hooks.