Reducing Boilerplate

Redux is in part inspired by Flux, and the most common complaint about Flux is how it makes you write a lot of boilerplate. In this recipe, we will consider how Redux lets us choose how verbose we'd like our code to be, depending on personal style, team preferences, longer term maintainability, and so on.

Actions

Actions are plain objects describing what happened in the app, and serve as the sole way to describe an intention to mutate the data. It's important that actions being objects you have to dispatch is not boilerplate, but one of the fundamental design choices of Redux.

There are frameworks claiming to be similar to Flux, but without a concept of action objects. In terms of being predictable, this is a step backwards from Flux or Redux. If there are no serializable plain object actions, it is impossible to record and replay user sessions, or to implement hot reloading with time travel. If you'd rather modify data directly, you don't need Redux.

Actions look like this:

  1. { type: 'ADD_TODO', text: 'Use Redux' }
  2. { type: 'REMOVE_TODO', id: 42 }
  3. { type: 'LOAD_ARTICLE', response: { ... } }

It is a common convention that actions have a constant type that helps reducers (or Stores in Flux) identify them. We recommend that you use strings and not Symbols for action types, because strings are serializable, and by using Symbols you make recording and replaying harder than it needs to be.

In Flux, it is traditionally thought that you would define every action type as a string constant:

  1. const ADD_TODO = 'ADD_TODO'
  2. const REMOVE_TODO = 'REMOVE_TODO'
  3. const LOAD_ARTICLE = 'LOAD_ARTICLE'

Why is this beneficial? It is often claimed that constants are unnecessary, and for small projects, this might be correct. For larger projects, there are some benefits to defining action types as constants:

  • It helps keep the naming consistent because all action types are gathered in a single place.
  • Sometimes you want to see all existing actions before working on a new feature. It may be that the action you need was already added by somebody on the team, but you didn't know.
  • The list of action types that were added, removed, and changed in a Pull Request helps everyone on the team keep track of scope and implementation of new features.
  • If you make a typo when importing an action constant, you will get undefined. Redux will immediately throw when dispatching such an action, and you'll find the mistake sooner.
    It is up to you to choose the conventions for your project. You may start by using inline strings, and later transition to constants, and maybe later group them into a single file. Redux does not have any opinion here, so use your best judgment.

Action Creators

It is another common convention that, instead of creating action objects inline in the places where you dispatch the actions, you would create functions generating them.

For example, instead of calling dispatch with an object literal:

  1. // somewhere in an event handler
  2. dispatch({
  3. type: 'ADD_TODO',
  4. text: 'Use Redux'
  5. })

You might write an action creator in a separate file, and import it into your component:

actionCreators.js

  1. export function addTodo(text) {
  2. return {
  3. type: 'ADD_TODO',
  4. text
  5. }
  6. }

AddTodo.js

  1. import { addTodo } from './actionCreators'
  2. // somewhere in an event handler
  3. dispatch(addTodo('Use Redux'))

Action creators have often been criticized as boilerplate. Well, you don't have to write them! You can use object literals if you feel this better suits your project. There are, however, some benefits for writing action creators you should know about.

Let's say a designer comes back to us after reviewing our prototype, and tells us that we need to allow three todos maximum. We can enforce this by rewriting our action creator to a callback form with redux-thunk middleware and adding an early exit:

  1. function addTodoWithoutCheck(text) {
  2. return {
  3. type: 'ADD_TODO',
  4. text
  5. }
  6. }
  7. export function addTodo(text) {
  8. // This form is allowed by Redux Thunk middleware
  9. // described below in “Async Action Creators” section.
  10. return function(dispatch, getState) {
  11. if (getState().todos.length === 3) {
  12. // Exit early
  13. return
  14. }
  15. dispatch(addTodoWithoutCheck(text))
  16. }
  17. }

We just modified how the addTodo action creator behaves, completely invisible to the calling code. We don't have to worry about looking at each place where todos are being added, to make sure they have this check. Action creators let you decouple additional logic around dispatching an action, from the actual components emitting those actions. It's very handy when the application is under heavy development, and the requirements change often.

Generating Action Creators

Some frameworks like Flummox generate action type constants automatically from the action creator function definitions. The idea is that you don't need to both define ADD_TODO constant and addTodo() action creator. Under the hood, such solutions still generate action type constants, but they're created implicitly so it's a level of indirection and can cause confusion. We recommend creating your action type constants explicitly.

Writing simple action creators can be tiresome and often ends up generating redundant boilerplate code:

  1. export function addTodo(text) {
  2. return {
  3. type: 'ADD_TODO',
  4. text
  5. }
  6. }
  7. export function editTodo(id, text) {
  8. return {
  9. type: 'EDIT_TODO',
  10. id,
  11. text
  12. }
  13. }
  14. export function removeTodo(id) {
  15. return {
  16. type: 'REMOVE_TODO',
  17. id
  18. }
  19. }

You can always write a function that generates an action creator:

  1. function makeActionCreator(type, ...argNames) {
  2. return function(...args) {
  3. const action = { type }
  4. argNames.forEach((arg, index) => {
  5. action[argNames[index]] = args[index]
  6. })
  7. return action
  8. }
  9. }
  10. const ADD_TODO = 'ADD_TODO'
  11. const EDIT_TODO = 'EDIT_TODO'
  12. const REMOVE_TODO = 'REMOVE_TODO'
  13. export const addTodo = makeActionCreator(ADD_TODO, 'text')
  14. export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'text')
  15. export const removeTodo = makeActionCreator(REMOVE_TODO, 'id')

There are also utility libraries to aid in generating action creators, such as redux-act and redux-actions. These can help reduce boilerplate code and enforce adherence to standards such as Flux Standard Action (FSA).

Async Action Creators

Middleware lets you inject custom logic that interprets every action object before it is dispatched. Async actions are the most common use case for middleware.

Without any middleware, dispatch only accepts a plain object, so we have to perform AJAX calls inside our components:

actionCreators.js

  1. export function loadPostsSuccess(userId, response) {
  2. return {
  3. type: 'LOAD_POSTS_SUCCESS',
  4. userId,
  5. response
  6. }
  7. }
  8. export function loadPostsFailure(userId, error) {
  9. return {
  10. type: 'LOAD_POSTS_FAILURE',
  11. userId,
  12. error
  13. }
  14. }
  15. export function loadPostsRequest(userId) {
  16. return {
  17. type: 'LOAD_POSTS_REQUEST',
  18. userId
  19. }
  20. }

UserInfo.js

  1. import { Component } from 'react'
  2. import { connect } from 'react-redux'
  3. import {
  4. loadPostsRequest,
  5. loadPostsSuccess,
  6. loadPostsFailure
  7. } from './actionCreators'
  8. class Posts extends Component {
  9. loadData(userId) {
  10. // Injected into props by React Redux `connect()` call:
  11. const { dispatch, posts } = this.props
  12. if (posts[userId]) {
  13. // There is cached data! Don't do anything.
  14. return
  15. }
  16. // Reducer can react to this action by setting
  17. // `isFetching` and thus letting us show a spinner.
  18. dispatch(loadPostsRequest(userId))
  19. // Reducer can react to these actions by filling the `users`.
  20. fetch(`http://myapi.com/users/${userId}/posts`).then(
  21. response => dispatch(loadPostsSuccess(userId, response)),
  22. error => dispatch(loadPostsFailure(userId, error))
  23. )
  24. }
  25. componentDidMount() {
  26. this.loadData(this.props.userId)
  27. }
  28. componentDidUpdate(prevProps) {
  29. if (prevProps.userId !== this.props.userId) {
  30. this.loadData(this.props.userId)
  31. }
  32. }
  33. render() {
  34. if (this.props.isFetching) {
  35. return <p>Loading...</p>
  36. }
  37. const posts = this.props.posts.map(post => (
  38. <Post post={post} key={post.id} />
  39. ))
  40. return <div>{posts}</div>
  41. }
  42. }
  43. export default connect(state => ({
  44. posts: state.posts,
  45. isFetching: state.isFetching
  46. }))(Posts)

However, this quickly gets repetitive because different components request data from the same API endpoints. Moreover, we want to reuse some of this logic (e.g., early exit when there is cached data available) from many components.

Middleware lets us write more expressive, potentially async action creators. It lets us dispatch something other than plain objects, and interprets the values. For example, middleware can “catch” dispatched Promises and turn them into a pair of request and success/failure actions.

The simplest example of middleware is redux-thunk. “Thunk” middleware lets you write action creators as “thunks”, that is, functions returning functions. This inverts the control: you will get dispatch as an argument, so you can write an action creator that dispatches many times.

Note

Thunk middleware is just one example of middleware. Middleware is not about “letting you dispatch functions”. It's about letting you dispatch anything that the particular middleware you use knows how to handle. Thunk middleware adds a specific behavior when you dispatch functions, but it really depends on the middleware you use.

Consider the code above rewritten with redux-thunk:

actionCreators.js

  1. export function loadPosts(userId) {
  2. // Interpreted by the thunk middleware:
  3. return function(dispatch, getState) {
  4. const { posts } = getState()
  5. if (posts[userId]) {
  6. // There is cached data! Don't do anything.
  7. return
  8. }
  9. dispatch({
  10. type: 'LOAD_POSTS_REQUEST',
  11. userId
  12. })
  13. // Dispatch vanilla actions asynchronously
  14. fetch(`http://myapi.com/users/${userId}/posts`).then(
  15. response =>
  16. dispatch({
  17. type: 'LOAD_POSTS_SUCCESS',
  18. userId,
  19. response
  20. }),
  21. error =>
  22. dispatch({
  23. type: 'LOAD_POSTS_FAILURE',
  24. userId,
  25. error
  26. })
  27. )
  28. }
  29. }

UserInfo.js

  1. import { Component } from 'react'
  2. import { connect } from 'react-redux'
  3. import { loadPosts } from './actionCreators'
  4. class Posts extends Component {
  5. componentDidMount() {
  6. this.props.dispatch(loadPosts(this.props.userId))
  7. }
  8. componentDidUpdate(prevProps) {
  9. if (prevProps.userId !== this.props.userId) {
  10. this.props.dispatch(loadPosts(this.props.userId))
  11. }
  12. }
  13. render() {
  14. if (this.props.isFetching) {
  15. return <p>Loading...</p>
  16. }
  17. const posts = this.props.posts.map(post => (
  18. <Post post={post} key={post.id} />
  19. ))
  20. return <div>{posts}</div>
  21. }
  22. }
  23. export default connect(state => ({
  24. posts: state.posts,
  25. isFetching: state.isFetching
  26. }))(Posts)

This is much less typing! If you'd like, you can still have “vanilla” action creators like loadPostsSuccess which you'd use from a container loadPosts action creator.

Finally, you can write your own middleware. Let's say you want to generalize the pattern above and describe your async action creators like this instead:

  1. export function loadPosts(userId) {
  2. return {
  3. // Types of actions to emit before and after
  4. types: ['LOAD_POSTS_REQUEST', 'LOAD_POSTS_SUCCESS', 'LOAD_POSTS_FAILURE'],
  5. // Check the cache (optional):
  6. shouldCallAPI: state => !state.posts[userId],
  7. // Perform the fetching:
  8. callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`),
  9. // Arguments to inject in begin/end actions
  10. payload: { userId }
  11. }
  12. }

The middleware that interprets such actions could look like this:

  1. function callAPIMiddleware({ dispatch, getState }) {
  2. return next => action => {
  3. const { types, callAPI, shouldCallAPI = () => true, payload = {} } = action
  4. if (!types) {
  5. // Normal action: pass it on
  6. return next(action)
  7. }
  8. if (
  9. !Array.isArray(types) ||
  10. types.length !== 3 ||
  11. !types.every(type => typeof type === 'string')
  12. ) {
  13. throw new Error('Expected an array of three string types.')
  14. }
  15. if (typeof callAPI !== 'function') {
  16. throw new Error('Expected callAPI to be a function.')
  17. }
  18. if (!shouldCallAPI(getState())) {
  19. return
  20. }
  21. const [requestType, successType, failureType] = types
  22. dispatch(
  23. Object.assign({}, payload, {
  24. type: requestType
  25. })
  26. )
  27. return callAPI().then(
  28. response =>
  29. dispatch(
  30. Object.assign({}, payload, {
  31. response,
  32. type: successType
  33. })
  34. ),
  35. error =>
  36. dispatch(
  37. Object.assign({}, payload, {
  38. error,
  39. type: failureType
  40. })
  41. )
  42. )
  43. }
  44. }

After passing it once to applyMiddleware(…middlewares), you can write all your API-calling action creators the same way:

  1. export function loadPosts(userId) {
  2. return {
  3. types: ['LOAD_POSTS_REQUEST', 'LOAD_POSTS_SUCCESS', 'LOAD_POSTS_FAILURE'],
  4. shouldCallAPI: state => !state.posts[userId],
  5. callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`),
  6. payload: { userId }
  7. }
  8. }
  9. export function loadComments(postId) {
  10. return {
  11. types: [
  12. 'LOAD_COMMENTS_REQUEST',
  13. 'LOAD_COMMENTS_SUCCESS',
  14. 'LOAD_COMMENTS_FAILURE'
  15. ],
  16. shouldCallAPI: state => !state.comments[postId],
  17. callAPI: () => fetch(`http://myapi.com/posts/${postId}/comments`),
  18. payload: { postId }
  19. }
  20. }
  21. export function addComment(postId, message) {
  22. return {
  23. types: [
  24. 'ADD_COMMENT_REQUEST',
  25. 'ADD_COMMENT_SUCCESS',
  26. 'ADD_COMMENT_FAILURE'
  27. ],
  28. callAPI: () =>
  29. fetch(`http://myapi.com/posts/${postId}/comments`, {
  30. method: 'post',
  31. headers: {
  32. Accept: 'application/json',
  33. 'Content-Type': 'application/json'
  34. },
  35. body: JSON.stringify({ message })
  36. }),
  37. payload: { postId, message }
  38. }
  39. }

Reducers

Redux reduces the boilerplate of Flux stores considerably by describing the update logic as a function. A function is simpler than an object, and much simpler than a class.

Consider this Flux store:

  1. const _todos = []
  2. const TodoStore = Object.assign({}, EventEmitter.prototype, {
  3. getAll() {
  4. return _todos
  5. }
  6. })
  7. AppDispatcher.register(function(action) {
  8. switch (action.type) {
  9. case ActionTypes.ADD_TODO:
  10. const text = action.text.trim()
  11. _todos.push(text)
  12. TodoStore.emitChange()
  13. }
  14. })
  15. export default TodoStore

With Redux, the same update logic can be described as a reducing function:

  1. export function todos(state = [], action) {
  2. switch (action.type) {
  3. case ActionTypes.ADD_TODO:
  4. const text = action.text.trim()
  5. return [...state, text]
  6. default:
  7. return state
  8. }
  9. }

The switch statement is not the real boilerplate. The real boilerplate of Flux is conceptual: the need to emit an update, the need to register the Store with a Dispatcher, the need for the Store to be an object (and the complications that arise when you want a universal app).

It's unfortunate that many still choose Flux framework based on whether it uses switch statements in the documentation. If you don't like switch, you can solve this with a single function, as we show below.

Generating Reducers

Let's write a function that lets us express reducers as an object mapping from action types to handlers. For example, if we want our todos reducers to be defined like this:

  1. export const todos = createReducer([], {
  2. [ActionTypes.ADD_TODO]: (state, action) => {
  3. const text = action.text.trim()
  4. return [...state, text]
  5. }
  6. })

We can write the following helper to accomplish this:

  1. function createReducer(initialState, handlers) {
  2. return function reducer(state = initialState, action) {
  3. if (handlers.hasOwnProperty(action.type)) {
  4. return handlers[action.type](state, action)
  5. } else {
  6. return state
  7. }
  8. }
  9. }

This wasn't difficult, was it? Redux doesn't provide such a helper function by default because there are many ways to write it. Maybe you want it to automatically convert plain JS objects to Immutable objects to hydrate the server state. Maybe you want to merge the returned state with the current state. There may be different approaches to a “catch all” handler. All of this depends on the conventions you choose for your team on a specific project.

The Redux reducer API is (state, action) => newState, but how you create those reducers is up to you.