Sensible React Forms, with Govern

Creating forms with React can be a little tricky. Perhaps you decide to use Raw React, and end up repeating the same handler code each time you need a new field. Or maybe you force the non-global form state into a global Redux store. Either way, things get awkward quickly.

But luckily, React forms don’t have to be awkward. In fact, they can be downright easy. And the trick is simple: you just need to understand that form state isn’t like other state.

Three types of state

As it turns out, the problem is that web applications usually have three types of state, and we only talk about two of them.

1. View State

View state includes anything that is associated with the DOM itself. Examples include the state of animations and transitions.

React component state is great is a perfect way to store it, as each React component is tied to a DOM node.

2. Environment state

Environment state includes anything that is relevant throughout your entire application. Examples include the current user’s details, received data, or in-progress requests.

Redux is great at storing environment state, as you generally only have a single Redux store, which can be accessed anywhere via React context.

3. Control state

Control state includes anything associated with user interactions. Examples include the state of forms, selected items, and error messages.

The thing about control state is that it is associated with a specific part of the application, which may be loaded, disposed, or re-used in multiple places. This means that it isn’t environment state, and it doesn’t fit well in a global Redux store.

And while you can put form state in React components, it really doesn’t belong in them. After all, sometimes you want to keep your form state around after the DOM nodes disappear. Sure, you could lift your state up, except now you can’t easily re-use the logic. And isn’t React about reusable components?

But… what if you could define components that weren’t tied to the DOM?

Introducing Govern

Govern is a library for managing state with store components. These are a lot like React components – they can receive props, call setState, and define lifecycle methods. They can be defined as classes, or as stateless functions.

But instead of rendering elements, store components publish raw JavaScript, so they’re not tied to the DOM.

And the best thing? If you know React, then you already know most of Govern’s API, so you’ll be productive in no time. In fact, by the end of this short guide, you’ll be able to build a form with validation and connect it to a JSON API — and you’ll barely need to learn a thing!

So let’s get started by creating your first store component for managing form state.

Defining store components

Govern components are just JavaScript classes that extend Govern.Component. Like React components, they have props, state, and lifecycle methods.

For example, here’s how you’d create a Model component that handles state and validation for individual form fields:

import * as Govern from 'govern'

class Model extends Govern.Component {
  static defaultProps = {
    defaultValue: ''
  }

  constructor(props) {
    super(props)

    this.state = {
      value: props.defaultValue,
    }
  }

  publish() {
    let value = this.state.value
    let error = this.props.validate ? this.props.validate(value) : null

    return {
      value: this.state.value,
      error: error,
      change: this.change,
    }
  }

  change = (newValue) => {
    this.setState({
      value: newValue,
    })
  }
}

Govern components have one major difference from React components: instead of render(), they take a publish() method. This is where you specify the component’s output, which will be computed each time the component’s props or state change.

Subscribing to stores

Now that you have a Model component, the next step is to subscribe to its published values from inside of your React app.

Govern exports a <Subscribe to> React component to handle this for you. This component takes a Govern element for its to prop, and a render function for its children prop. It calls the render function with each new published value — just like React’s context API.

Here’s a barebones example that connects a <Model> to an input field, using <Subscribe>.

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { Subscribe } from 'react-govern'

ReactDOM.render(
  <Subscribe to={<Model validate={validateEmail} />}>
    {emailModel =>
      <label>
        Email: 
        <input
          value={emailModel.value}
          onChange={e => emailModel.change(e.target.value)}
        />
        {
          emailModel.error &&
          <p style={{color: 'red'}}>{emailModel.error}</p>
        }
      </label>
    }
  </Subscribe>,
  document.getElementById('root')
)

function validateEmail(value) {
  if (value.indexOf('@') === -1) {
    return "please enter a valid e-mail"
  }
}

Try it live at CodeSandbox »

Adding Govern to create-react-app

If you’d like to follow along and create your own app — which I’d highly recommend — then all you need to do is create a new app with create-react-app, and then add govern:

create-react-app govern-example
cd govern-example
npm install --save govern react-govern
npm run start

Once you’ve got Govern installed, you can just copy the above two code blocks into index.js, and you’re set! If you run into any trouble, take a look at the live example.


Did you get it to work? Then congratulations — you’ve just learned a new way to manage state! And all you need to remember is that:

  • Store components extend from Govern.Component in place of React.Component.
  • Store components use a publish method in place of render.
  • You can subscribe to store components with <Subscribe to>.

These three things will get you a long way. But I promised that you’d make a form component, and so far I’ve only demonstrated a field component…

Combining stores

Govern components have one special method that doesn’t exist on React components — subscribe().

When a component’s subscribe() method returns some Govern elements, the component will subscribe to those elements, placing their latest published values on the component’s subs instance property. You can then use the value of this.subs within the component’s publish() method, allowing you to combine store components.

For example, you could combine two <Model> elements to create a <RegistrationFormModel> component:

class RegistrationFormModel extends Govern.Component {
  static defaultProps = {
    defaultValue: { name: '', email: '' }
  }

  subscribe() {
    let defaultValue = this.props.defaultValue

    return {
      name: <Model defaultValue={defaultValue.name} validate={validateNotEmpty} />,
      email: <Model defaultValue={defaultValue.email} validate={validateEmail} />,
    }
  }

  publish() {
    return this.subs
  }
}

function validateNotEmpty(value) {
  if (!value) {
    return "please enter your name"
  }
}

Field view components

One of the benefits of using the same <Model> component for each field is that it makes creating reusable form views simpler. For example, you could create a <Field> React component to render your field models:

class Field extends React.Component {
  render() {
    return (
      <label style={{display: 'block'}}>
        <span>{this.props.label}</span>
        <input
          value={this.props.model.value}
          onChange={this.handleChange}
        />
        {
          this.props.model.error &&
          <p style={{color: 'red'}}>{this.props.model.error}</p>
        }
      </label>
    )
  }

  handleChange = (e) => {
    this.props.model.change(e.target.value)
  }
}

ReactDOM.render(
  <Subscribe to={<RegistrationFormModel />}>
    {model =>
      <div>
        <Field label='Name' model={model.name} />
        <Field label='E-mail' model={model.email} />
      </div>
    }
  </Subscribe>,
  document.getElementById('root')
)

Try it live at CodeSandbox ».

Stateless functional components

You’ll sometimes find yourself creating components that just subscribe() to a few elements, and then re-publish the outputs without any changes. Govern provides a shortcut for defining this type of component: just return the elements you want to subscribe to from a plain function — like React’s stateless functional components.

For example, you could convert the above <RegistrationFormModel> component to a stateless functional component:

const RegistrationFormModel = ({ defaultValue }) => ({
  name: <Model defaultValue={defaultValue.name} validate={validateNotEmpty} />,
  email: <Model defaultValue={defaultValue.email} validate={validateEmail} />
});

RegistrationFormModel.defaultProps = {
  defaultValue: { name: '', email: '' } 
}

Try it live at CodeSandbox ».

Calling a JSON API

Once you have some data in your form, submitting it is easy — you just publish a submit() handler along with the form data. Everything you know about handling HTTP requests in React components transfers over to Govern components.

However, Govern does give you an advantage over vanilla React — your requests can be components too!

For example, this component takes the request body as props, makes a request in the componentDidInstantiate() lifecycle method, and emits the request status via the publish() method.

Note: I use the axios package here to simplify the network code. If you’re following along, you can install it with npm install --save axios.

import * as axios from "axios";

class PostRegistrationRequest extends Govern.Component {
  state = {
    status: 'fetching',
  }

  publish() {
    return this.state
  }

  componentDidInstantiate() {
    axios.post('/user', this.props.data)
      .then(response => {
        if (!this.isDisposed) {
          this.setState({
            status: 'success',
            result: response.data,
          })
        }
      })
      .catch((error = {}) => {
        if (!this.isDisposed) {
          this.setState({
            status: 'error',
            message: error.message || "Unknown Error",
          })
        }
      });
  }

  componentWillBeDisposed() {
    this.isDisposed = true
  }
}

You can then make a request by subscribing to a new <PostRegistrationRequest> element.

class RegistrationFormController extends Govern.Component {
  state = {
    request: null
  };

  subscribe() {
    return {
      model: <RegistrationFormModel />,
      request: this.state.request
    };
  }

  publish() {
    return {
      ...this.subs,
      canSubmit: this.canSubmit(),
      submit: this.submit
    };
  }

  canSubmit() {
    return (
      !this.subs.model.email.error &&
      !this.subs.model.name.error &&
      (!this.subs.request || this.subs.request.status === "error")
    );
  }

  submit = e => {
    e.preventDefault();

    if (this.canSubmit()) {
      let data = {
        email: this.subs.model.email.value,
        name: this.subs.model.name.value
      };

      this.setState({
        request: (
          <PostRegistrationRequest data={data} key={new Date().getTime()} />
        )
      });
    }
  };
}

ReactDOM.render(
  <Subscribe to={<RegistrationFormController />}>
    {({ canSubmit, model, request, submit }) => (
      <form onSubmit={submit}>
        {request &&
          request.status === "error" && (
            <p style={{ color: "red" }}>{request.message}</p>
          )}
        <Field label="Name" model={model.name} />
        <Field label="E-mail" model={model.email} />
        <button type="submit" disabled={!canSubmit}>
          Register
        </button>
      </form>
    )}
  </Subscribe>,
  document.getElementById("root")
);

Try it live at CodeSandbox ».

Did you see how the key prop is used in the above example? Just like React, changing key will result in a new component instance being created, and thus a new request being made each time the user clicks “Register”.

While request components can take a little getting used to, they have the benefit of being able to publish multiple statuses over time — where promises can only publish one. For example, you could publish disconnected or unauthenticated states, along with a retry() action to give the request another crack.

Request components also make it easy to share communication logic within and between applications. For an example, I use a <Request> component within my own applications.

Performance note: selecting data

Govern’s <Subscribe> component needs to call its render prop each time that any part of its output changes. This is great for small components, but as the output gets larger and more complicated, the number of re-renders will also grow — and a perceivable delay can creep into user interactions.

Where possible, you should stick to <Subscribe>. But in the rare case that there is noticeable lag, you can use Govern’s <Store of> component to instantiate a Store object, which allows you to manually manage subscriptions.

Once you have a Store object, there are two ways you can use it:

  • You can access the latest output with its getValue() method.
  • You can return the store from a component’s subscribe() method, and then republish the individual parts that you want.

For example, here’s how the above example would look with a <Store of> component. Note that this adds a fair amount of complexity — try to stick to <Subscribe to> unless performance becomes an issue.

class MapDistinct extends Govern.Component {
  subscribe() {
    return this.props.from
  }
  shouldComponentUpdate(nextProps, nextState, nextSubs) {
    return nextProps.to(nextSubs) !== this.props.to(this.subs)
  }
  publish() {
    return this.props.to(this.subs)
  }
}

const Field = ({ model, label }) => (
  <Subscribe to={model}>
    {model => (
      <label style={{ display: "block" }}>
        <span>{label}</span>
        <input
          value={model.value}
          onChange={e => model.change(e.target.value)}
        />
        {model.error && <p style={{ color: "red" }}>{model.error}</p>}
      </label>
    )}
  </Subscribe>
);

ReactDOM.render(
  <Store of={<RegistrationFormController />}>
    {store => (
      <form onSubmit={store.getValue().submit}>
        <Subscribe
          to={<MapDistinct from={store} to={output => output.request} />}
        >
          {request =>
            request && request.status === "error" ? (
              <p style={{ color: "red" }}>{request.message}</p>
            ) : null
          }
        </Subscribe>
        <Field
          label="Name"
          model={<MapDistinct from={store} to={output => output.model.name} />}
        />
        <Field
          label="E-mail"
          model={<MapDistinct from={store} to={output => output.model.email} />}
        />
        <Subscribe
          to={<MapDistinct from={store} to={output => output.canSubmit} />}
        >
          {canSubmit => (
            <button type="submit" disabled={!canSubmit}>
              Register
            </button>
          )}
        </Subscribe>
      </form>
    )}
  </Store>,
  document.getElementById("root")
);

Try it live at CodeSandbox ».

Note how the above example uses getValue() to access the submit() action, but uses <Subscribe> elsewhere. This is because we know that submit won’t change, and thus we don’t need to subscribe to future values.

Also note how the selector component defines a shouldComponentUpdate() method. If this wasn’t defined, then each update to the from store would cause a new publish — even if the published value didn’t change! Defining shouldComponentUpdate() gives you control over exactly which changes cause a publish — just like with React.

Built-in components

Govern has a number of built-in elements to help you reduce boilerplate and accomplish common tasks. These are particularly useful for creating selector components.

The three built-ins that you’ll use most often are:

  1. <map from={Store | Element} to={output => mappedOutput} />

Maps the output of from, using the function passed to to. Each publish on the from store will result in a new publish.

  1. <flatMap from={Store | Element} to={output => mappedElement} />

Maps the output of from, using the output of whatever element is returned by to. Each published of the mapped element results in a new publish.

  1. <distinct by?={(x, y) => boolean} children>

Publishes the output of the child element, but only when it differs from the previous output. By default, outputs are compared using reference equality, but you can supply a custom comparison function via the by prop.


For example, you could use the <flatMap> and <distinct> built-ins to rewrite the <MapDistinct> component from the previous example as a stateless functional component.

const MapDistinct = props => (
  <distinct>
    <map from={props.from} to={props.to} />
  </distinct>
);

Try it live at CodeSandbox ».

What next?

Believe it or not, you’ve just learned enough about Govern to make useful applications with it. Congratulations!

In fact, I already use Govern in my own projects. I wouldn’t yet recommend it for critical applications, but with your help, it will continue to steadily involve.

If you do find any issues while using Govern, and find the time to file an issue, you’ll be my new best friend. I’m also extremely open to pull requests, and would be happy to help get the word out about any components you’d like to share.

Finally, if you like what you see, please let me know with a star on GitHub! And if you want to hear more about Govern, join my newsletter below – I’ll even throw in a few PDF cheatsheets as thanks!

I will send you useful articles, cheatsheets and code.

I won't send you useless inbox filler. No spam, ever.
Unsubscribe at any time.

Thanks for reading, and until next time, happy Governing!

Leave a Reply

Your email address will not be published.