Managing state in React is hard. Especially when writing simple forms. Let’s see how we can replace repetitive boilerplate code with higher order functions. This may or may not be overkill, but it is a fun exercise nonetheless.

So, let’s consider a simple Register form given in plain HTML:

So far nothing out of the ordinary. But sadly, we need to mix in some variables and functions to make it interactive. The end result is a React stateless component that looks something like this:

OK, that still resembles our form from before with just enough code added to really make it functional. But, where will we keep the state? Let’s use simple Javascript object for that:

So we have our backing field for username , password and helper flag for progress. Our ‘logic’ is contained in a simple function that simulates callback based async function. Notice that we are calling setState on this mysterious object named r ! What kind of sorcery is that?

Well, it kinda implies that it is some sort of React component (if the letter r isn’t a hint, maybe the fact that we are calling setState on it is a giveaway). It seems that the state is contained in r and that it will also handle correct state management. We also are not using this , instead we are accessing state via the same object.

To create reusable stateful components we must resort to using higher order components (also known as HOCs). What we need is a function that will create a new component on the fly and that component will correctly handle state changes, wire properties and event handlers. Simplest HOC that does nothing looks like:

The above component does nothing, but it serves as a starting point. Our HOC will forward properties from the state object as props, rewrite functions to enable changing internal state and also supply default implementation for basic input handling. It looks like this:

We can see naive implementation for our set function there as well as forwarding state as props. Notice how functions in the specified state are rebound to include React component. This allows for the mysterious r to work.

Using HOC is simple:

export default wrap(registration, RegisterForm)

And voila, we now have clearly separated business logic from our simple presentation component.