Action Creators

Learn how to use action creators.

As our applications grow and develop, we will start encountering more and more code like this:

store.dispatch({
  type: 'ADD_RECIPE',
  title: title.trim(),
  description: description ? description.trim() : ''
});

If we decide to use the same action in other places, we will end up having to duplicate the logic in multiple locations and remember all the parameters. This code will be hard to maintain, as we will have to synchronize the changes between all the action occurrences.

A better approach is to keep the code in one place. We can create a function that will create the action object for us:

const addRecipe = (title, description = '') => ({
  type: 'ADD_RECIPE',
  title: title.trim(),
  description:description.trim()
});

Now we can use it in our code:

store.dispatch(addRecipe(title, description));

The action creator can now handle any modification to the content or logic of the action.

Beyond improving the maintainability of our applications, moving the action object creation into a function allows us to write simpler tests. We can test the logic separately from the places where the function is called.

In a large project, most of our actions will have a corresponding action creator function. We will try never to call the dispatch() method by manually creating the appropriate action object but using an action creator. This might appear to be a lot of overhead initially, but its value will become apparent as the project grows.

Get hands-on with 1400+ tech skills courses.