Reducers

Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.

Designing the State Shape

In Redux, all the application state is stored as a single object. It's a good idea to think of its shape before writing any code. What's the minimal representation of your app's state as an object?

For our todo app, we want to store two different things:

  • The currently selected visibility filter.
  • The actual list of todos.
    You'll often find that you need to store some data, as well as some UI state, in the state tree. This is fine, but try to keep the data separate from the UI state.
  1. {
  2. visibilityFilter: 'SHOW_ALL',
  3. todos: [
  4. {
  5. text: 'Consider using Redux',
  6. completed: true
  7. },
  8. {
  9. text: 'Keep all state in a single tree',
  10. completed: false
  11. }
  12. ]
  13. }
Note on Relationships

In a more complex app, you're going to want different entities to reference each other. We suggest that you keep your state as normalized as possible, without any nesting. Keep every entity in an object stored with an ID as a key, and use IDs to reference it from other entities, or lists. Think of the app's state as a database. This approach is described in normalizr's documentation in detail. For example, keeping todosById: { id -> todo } and todos: array<id> inside the state would be a better idea in a real app, but we're keeping the example simple.

Handling Actions

Now that we've decided what our state object looks like, we're ready to write a reducer for it. The reducer is a pure function that takes the previous state and an action, and returns the next state.

  1. (previousState, action) => newState

It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue). It's very important that the reducer stays pure. Things you should never do inside a reducer:

  • Mutate its arguments;
  • Perform side effects like API calls and routing transitions;
  • Call non-pure functions, e.g. Date.now() or Math.random().
    We'll explore how to perform side effects in the advanced walkthrough. For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

With this out of the way, let's start writing our reducer by gradually teaching it to understand the actions we defined earlier.

We'll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:

  1. import { VisibilityFilters } from './actions'
  2. const initialState = {
  3. visibilityFilter: VisibilityFilters.SHOW_ALL,
  4. todos: []
  5. }
  6. function todoApp(state, action) {
  7. if (typeof state === 'undefined') {
  8. return initialState
  9. }
  10. // For now, don't handle any actions
  11. // and just return the state given to us.
  12. return state
  13. }

One neat trick is to use the ES6 default arguments syntax to write this in a more compact way:

  1. function todoApp(state = initialState, action) {
  2. // For now, don't handle any actions
  3. // and just return the state given to us.
  4. return state
  5. }

Now let's handle SET_VISIBILITY_FILTER. All it needs to do is to change visibilityFilter on the state. Easy:

  1. function todoApp(state = initialState, action) {
  2. switch (action.type) {
  3. case SET_VISIBILITY_FILTER:
  4. return Object.assign({}, state, {
  5. visibilityFilter: action.filter
  6. })
  7. default:
  8. return state
  9. }
  10. }

Note that:

  • We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { …state, …newState } instead.

  • We return the previous state in the default case. It's important to return the previous state for any unknown action.

Note on Object.assign

Object.assign() is a part of ES6, and is not supported by older browsers. To support them, you will need to either use a polyfill, a Babel plugin, or a helper from another library like _.assign().

Note on switch and Boilerplate

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). Redux solves these problems by using pure reducers instead of event emitters.

It's unfortunate that many still choose a framework based on whether it uses switch statements in the documentation. If you don't like switch, you can use a custom createReducer function that accepts a handler map, as shown in “reducing boilerplate”.

Handling More Actions

We have two more actions to handle! Just like we did with SET_VISIBILITY_FILTER, we'll import the ADD_TODO and TOGGLE_TODO actions and then extend our reducer to handle ADD_TODO.

  1. import {
  2. ADD_TODO,
  3. TOGGLE_TODO,
  4. SET_VISIBILITY_FILTER,
  5. VisibilityFilters
  6. } from './actions'
  7. ...
  8. function todoApp(state = initialState, action) {
  9. switch (action.type) {
  10. case SET_VISIBILITY_FILTER:
  11. return Object.assign({}, state, {
  12. visibilityFilter: action.filter
  13. })
  14. case ADD_TODO:
  15. return Object.assign({}, state, {
  16. todos: [
  17. ...state.todos,
  18. {
  19. text: action.text,
  20. completed: false
  21. }
  22. ]
  23. })
  24. default:
  25. return state
  26. }
  27. }

Just like before, we never write directly to state or its fields, and instead we return new objects. The new todos is equal to the old todos concatenated with a single new item at the end. The fresh todo was constructed using the data from the action.

Finally, the implementation of the TOGGLE_TODO handler shouldn't come as a complete surprise:

  1. case TOGGLE_TODO:
  2. return Object.assign({}, state, {
  3. todos: state.todos.map((todo, index) => {
  4. if (index === action.index) {
  5. return Object.assign({}, todo, {
  6. completed: !todo.completed
  7. })
  8. }
  9. return todo
  10. })
  11. })

Because we want to update a specific item in the array without resorting to mutations, we have to create a new array with the same items except the item at the index. If you find yourself often writing such operations, it's a good idea to use a helper like immutability-helper, updeep, or even a library like Immutable that has native support for deep updates. Just remember to never assign to anything inside the state unless you clone it first.

Splitting Reducers

Here is our code so far. It is rather verbose:

  1. function todoApp(state = initialState, action) {
  2. switch (action.type) {
  3. case SET_VISIBILITY_FILTER:
  4. return Object.assign({}, state, {
  5. visibilityFilter: action.filter
  6. })
  7. case ADD_TODO:
  8. return Object.assign({}, state, {
  9. todos: [
  10. ...state.todos,
  11. {
  12. text: action.text,
  13. completed: false
  14. }
  15. ]
  16. })
  17. case TOGGLE_TODO:
  18. return Object.assign({}, state, {
  19. todos: state.todos.map((todo, index) => {
  20. if (index === action.index) {
  21. return Object.assign({}, todo, {
  22. completed: !todo.completed
  23. })
  24. }
  25. return todo
  26. })
  27. })
  28. default:
  29. return state
  30. }
  31. }

Is there a way to make it easier to comprehend? It seems like todos and visibilityFilter are updated completely independently. Sometimes state fields depend on one another and more consideration is required, but in our case we can easily split updating todos into a separate function:

  1. function todos(state = [], action) {
  2. switch (action.type) {
  3. case ADD_TODO:
  4. return [
  5. ...state,
  6. {
  7. text: action.text,
  8. completed: false
  9. }
  10. ]
  11. case TOGGLE_TODO:
  12. return state.map((todo, index) => {
  13. if (index === action.index) {
  14. return Object.assign({}, todo, {
  15. completed: !todo.completed
  16. })
  17. }
  18. return todo
  19. })
  20. default:
  21. return state
  22. }
  23. }
  24. function todoApp(state = initialState, action) {
  25. switch (action.type) {
  26. case SET_VISIBILITY_FILTER:
  27. return Object.assign({}, state, {
  28. visibilityFilter: action.filter
  29. })
  30. case ADD_TODO:
  31. return Object.assign({}, state, {
  32. todos: todos(state.todos, action)
  33. })
  34. case TOGGLE_TODO:
  35. return Object.assign({}, state, {
  36. todos: todos(state.todos, action)
  37. })
  38. default:
  39. return state
  40. }
  41. }

Note that todos also accepts state—but state is an array! Now todoApp gives todos just a slice of the state to manage, and todos knows how to update just that slice. This is called reducer composition, and it's the fundamental pattern of building Redux apps.

Let's explore reducer composition more. Can we also extract a reducer managing just visibilityFilter? We can.

Below our imports, let's use ES6 Object Destructuring to declare SHOW_ALL:

  1. const { SHOW_ALL } = VisibilityFilters

Then:

  1. function visibilityFilter(state = SHOW_ALL, action) {
  2. switch (action.type) {
  3. case SET_VISIBILITY_FILTER:
  4. return action.filter
  5. default:
  6. return state
  7. }
  8. }

Now we can rewrite the main reducer as a function that calls the reducers managing parts of the state, and combines them into a single object. It also doesn't need to know the complete initial state anymore. It's enough that the child reducers return their initial state when given undefined at first.

  1. function todos(state = [], action) {
  2. switch (action.type) {
  3. case ADD_TODO:
  4. return [
  5. ...state,
  6. {
  7. text: action.text,
  8. completed: false
  9. }
  10. ]
  11. case TOGGLE_TODO:
  12. return state.map((todo, index) => {
  13. if (index === action.index) {
  14. return Object.assign({}, todo, {
  15. completed: !todo.completed
  16. })
  17. }
  18. return todo
  19. })
  20. default:
  21. return state
  22. }
  23. }
  24. function visibilityFilter(state = SHOW_ALL, action) {
  25. switch (action.type) {
  26. case SET_VISIBILITY_FILTER:
  27. return action.filter
  28. default:
  29. return state
  30. }
  31. }
  32. function todoApp(state = {}, action) {
  33. return {
  34. visibilityFilter: visibilityFilter(state.visibilityFilter, action),
  35. todos: todos(state.todos, action)
  36. }
  37. }

Note that each of these reducers is managing its own part of the global state. The state parameter is different for every reducer, and corresponds to the part of the state it manages.

This is already looking good! When the app is larger, we can split the reducers into separate files and keep them completely independent and managing different data domains.

Finally, Redux provides a utility called combineReducers() that does the same boilerplate logic that the todoApp above currently does. With its help, we can rewrite todoApp like this:

  1. import { combineReducers } from 'redux'
  2. const todoApp = combineReducers({
  3. visibilityFilter,
  4. todos
  5. })
  6. export default todoApp

Note that this is equivalent to:

  1. export default function todoApp(state = {}, action) {
  2. return {
  3. visibilityFilter: visibilityFilter(state.visibilityFilter, action),
  4. todos: todos(state.todos, action)
  5. }
  6. }

You could also give them different keys, or call functions differently. These two ways to write a combined reducer are equivalent:

  1. const reducer = combineReducers({
  2. a: doSomethingWithA,
  3. b: processB,
  4. c: c
  5. })
  1. function reducer(state = {}, action) {
  2. return {
  3. a: doSomethingWithA(state.a, action),
  4. b: processB(state.b, action),
  5. c: c(state.c, action)
  6. }
  7. }

All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys, and combines their results into a single object again. It's not magic. And like other reducers, combineReducers() does not create a new object if all of the reducers provided to it do not change state.

Note for ES6 Savvy Users

Because combineReducers expects an object, we can put all top-level reducers into a separate file, export each reducer function, and use import * as reducers to get them as an object with their names as the keys:

  1. import { combineReducers } from 'redux'import as reducers from './reducers'const todoApp = combineReducers(reducers)

Because import is still new syntax, we don't use it anymore in the documentation to avoid confusion, but you may encounter it in some community examples.

Source Code

reducers.js

  1. import { combineReducers } from 'redux'
  2. import {
  3. ADD_TODO,
  4. TOGGLE_TODO,
  5. SET_VISIBILITY_FILTER,
  6. VisibilityFilters
  7. } from './actions'
  8. const { SHOW_ALL } = VisibilityFilters
  9. function visibilityFilter(state = SHOW_ALL, action) {
  10. switch (action.type) {
  11. case SET_VISIBILITY_FILTER:
  12. return action.filter
  13. default:
  14. return state
  15. }
  16. }
  17. function todos(state = [], action) {
  18. switch (action.type) {
  19. case ADD_TODO:
  20. return [
  21. ...state,
  22. {
  23. text: action.text,
  24. completed: false
  25. }
  26. ]
  27. case TOGGLE_TODO:
  28. return state.map((todo, index) => {
  29. if (index === action.index) {
  30. return Object.assign({}, todo, {
  31. completed: !todo.completed
  32. })
  33. }
  34. return todo
  35. })
  36. default:
  37. return state
  38. }
  39. }
  40. const todoApp = combineReducers({
  41. visibilityFilter,
  42. todos
  43. })
  44. export default todoApp

Next Steps

Next, we'll explore how to create a Redux store that holds the state and takes care of calling your reducer when you dispatch an action.