Skip to content
Haz edited this page Apr 2, 2017 · 6 revisions

Reducers are pure functions which are called sequentially when some action is dispatched. With them you can perform state changes based on the dispatched action.

A simple reducer will look like this:

const reducer = (state, action) => {
  switch (action.type) {
    case 'RESOURCE_CREATE':
      return {
        ...state,
        list: [action.detail, ...state.list],
      }
    default:
      return state
  }
}

Unit testing reducers

As well as actions, reducers are pure functions and therefore very easy to unit test:

it('adds the new data to the initial state', () => {
  expect(reducer({}, {
    type: 'RESOURCE_CREATE',
    data: {
      title: 'Hi!',
    },
  })).toEqual({
    list: [
      { title: 'Hi!' }
    ],
  })
})
Clone this wiki locally