Skip to content

Instantly share code, notes, and snippets.

@Emilios1995
Created March 30, 2017 03:28
Show Gist options
  • Save Emilios1995/0b0d34e60615a3b8053e84c2f4b942a9 to your computer and use it in GitHub Desktop.
Save Emilios1995/0b0d34e60615a3b8053e84c2f4b942a9 to your computer and use it in GitHub Desktop.
title published description cover_image tags
Rethinking Redux (and reducing its boilerplate)
true
How to make a single function to generate a reducer, action creators, and types
redux, react

tl;dr: redux-create-module

Suppose you want to create a new module in your react-redux app. You know the drill. Create the action type constants, make and the action creators, and handle the types in the reducer. You may have noticed that the process looks the same almost every time. We, as developers, know that this kind of things could, and should be abstracted and automated.

So, first let's think what's the best solution for Developer Experience. Or, since we are the Developers, let's just Rethink Redux.

Well, if we are only interested in mapping actions to states, my first thought is to make a Map. Or a regular object, for that matter.

https://gist.github.com/04365197f76ef6aff311ea766594596c

But we don't want to create the reducer. We only want to think about the Map. Let's make a function that takes a Map and returns a reducer

https://gist.github.com/d9a1bbf6c68381cd4ba017ceb6f4421b

So simple! Or, too simple! Because we have a problem here. Action creators were invented for a reason, and that's because some actions need to have a payload to be handled... Or is it? No! of course, there is another reason and that's because it's unsafe and ineffective to pass strings to the reducer. What if we make a typo on it?! So let's get more serious now.

We still don't want to create the action creators manually, and, why should we? Think about it, createReducer already has all the information it needs to make them. It can get the types of our actions from the keys of the Map. So, let's make it return both, a reducer and the action creators, and name it createModule

https://gist.github.com/0414a8231a831e30aa95f0da49bfc8f3

Neat!

Of course, we still have some todos. like namespacing our actions to avoid conflicts, and allowing a reducer to handle an action from another module. But we won't get into that in this post.

Instead, I'll refer you to the source of the little module I made.

Thanks for reading!

Photo: Sunrise in the Sea by me :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment