Working with forms in Redux can entail a significant amount of boilerplate. For instance, if you have a contact form with four fields: name, address, phone number and email, you might be tempted to define action types and action creators for each field e.g. EDIT_NAME
, EDIT_ADDRESS
, EDIT_PHONE_NUMBER
etc. With this approach, you might find yourself writing thousands of lines of code that basically all do the same thing.
Here’s a more scalable approach: We can define a reducer contactForm
to manage the form state using just 2 actions:
Here are the highlights of this approach:
- The reducer
contactForm
manages the form state in a plain object. - The initial state is the empty object
{}
. If you want the form to contain some default values, you can provide them in the initial state e.g.{ subscribeToNewsletter: true}
. - The reducer handles exactly two actions:
EDIT_CONTACT_FORM
, using which you can edit the values for one more fields, andCLEAR_CONTACT_FORM
, using which you can clear the contents of the form.
Here’s how we might use this reducer in our application:
Rather simple, isn’t it? If you want more granular control over the data, you can define additional selectors and action creators for specific fields:
It takes ~25 lines of code to define the reducer, action types and action creators, and ~10 lines to connect them with a React component. While we can do a lot better than this (more on that later), this is a fairly good starting point for reducing boilerplate while working with forms.