Quick Tip: alternative Redux reducers

I have been using a simple helper to simplify and reduce boilerplate for setting up reducers in Redux.

Redux reducers

What could be improved on the default “switch reducers”

Lets take a look at a default switch reducer:

What could be improved:

  • The switch statements are pretty ugly and unreadable, especially when they get bigger: you end up with splitting the reducer into functions, and in the switch statement calling those functions.
  • An action always has to return the original state, why do we need to do this everytime?
  • The default case always has to return the state, why do we need to add this in every reducer?

Lets improve the reducers boilerplate

Take a look at the following helper that I’ve using in most of my projects which simplifies the reducers:

Now lets convert the switch reducer to our new optimized reducer:

Final thoughts

So as you can see we cleaned up the reducer. I suggest you create a createReducer.js helper and play around with it, it made my code more readable which is imo the most important thing.

Enjoy writing less boilerplate code for your Redux reducers.