›API Reference

Introduction

Using Redux Starter Kit

API Reference

createReducer()

A utility that simplifies creating Redux reducer functions, by defining them as lookup tables of functions to handle each action type. It also allows you to drastically simplify immutable update logic, by writing "mutative" code inside your reducers.

Redux reducers are often implemented using a switch statement, with one case for every handled action type.

This approach works well, but is a bit boilerplate-y and error-prone. For instance, it is easy to forget the default case or setting the initial state.

The createReducer helper streamlines the implementation of such reducers. It takes two arguments. The first one is the initial state. The second is an object mapping from action types to case reducers, each of which handles one specific action type.

Action creators that were generated using createAction may be used directly as the keys here, using
computed property syntax. (If you are using TypeScript, you may have to use actionCreator.type or actionCreator.toString()
to force the TS compiler to accept the computed property.)

Direct State Mutation

Redux requires reducer functions to be pure and treat state values as immutable. While this is essential for making state updates predictable and observable, it can sometimes make the implementation of such updates awkward. Consider the following example:

The addTodo reducer is pretty easy to follow if you know the ES6 spread syntax. However, the code for toggleTodo is much less straightforward, especially considering that it only sets a single flag.

To make things easier, createReducer uses immer to let you write reducers as if they were mutating the state directly. In reality, the reducer receives a proxy state that translates all mutations into equivalent copy operations.

If you choose to write reducers in this style, make sure to learn about the pitfalls mentioned in the immer docs . Most importantly, you need to ensure that you either mutate the state argument or return a new state, but not both. For example, the following reducer would throw an exception if a toggleTodo action is passed: