Writing Reusable Redux Like a Boss

Felix Tan
5 min readApr 15, 2018

--

Overview: In this article, we’ll try to ease ourself from both physical and emotional pain on rewriting the same Redux logics over and over again in our application with Generator and Selector pattern. You can see the example implementation here: DEMO

I’mma sleep here while you’re repeatedly rewriting the same redux logics over and over again

If you’re Javascript hipsters like myself, chances are you won’t miss the hype of React and its ecosystem in the past few years. React and its tagline Learn once, Write Anywhere allows JS developers to declaratively build their user interfaces in not just on the Web, but also Mobile apps and also Virtual Reality. When talking about React apps, there’s one thing that you can’t possibly miss. Yep, you guessed it, it’s Redux!

Redux Key Principles

Redux offers a simple way to separate and manage our app’s states so those states won’t ended up cluttering our UI codes like in good ol’ jQuery days. To do this, redux introduces three basic principles that composes the whole Redux ecosystem:

ActionsThe payloads that used by our application to interact with Redux. Actions are the only source of information that can get in to our store. To create actions, usually we use an Action Creators, they’re basically a function that receives input and produces actions based on the given input.

The Action Creators

Reducers — Reducers are a function that acts as sets of rules that tell our Store how it should react to actions that are passed on to them.

The Reducers

Store — The single object tree that holds the whole states in our application.

The Store that wraps it all

It is acceptable to use simple implementations like above if we used every redux logics only once in a single part of our application, however, we’ll start to see code duplication if we wants to reuse the same logics in - i.e. different pages in our application. For example, let’s say we have a news app that wants to fetch different news in Home page and Newsfeed Page but uses the same logics, we might wrote it like this:

Home Page

Let’s pray we won’t have to write this again somewhere…

Newsfeed Page

Ouch! same codes, only different namespace, duh!

This requires us to rewrite the same code over and over again, and if there’s a future change on how we should handle the news data, we’ll have to find and change every pages that implements the same logics. Since we’re too lazy to do this, it is obvious for us to find a good solution to solve this dire problem.

The Generators

Since Redux key principles are just some plain functions that built on functional concepts, we can create simple generator functions to help us generate these objects for each usage/pages that needs to implement the same redux logics.

Our generator functions would receive the page’s name and implementation detail of the Redux principle that we’ll going to generate:

Type Generator

This generator function’s purpose is simple, append page’s name to action type string with delimiter of your choice, general convention uses / as redux page name delimiter, but you’re good to go with your personal preferences:

Type Generator will help us generate action types

Action Creators Generator

Action Creators Generator will help us generate the necessary action creators based on our page’s name.

Action Creators Generator will help in generating action creators

Action Handler Generator

Action Handler Generator helps in generating action handlers object to be used by our reducer. What is action handler? I’ll explain it after this section.

Action Handler Generator will help in generating action handler object

Reducer Generator

Reducer generator with the help of Action Handler Generator will help in generating the necessary reducer.

Reducer Generator will -not surprisingly- generate our reducer

Writing the common redux logics

You might asks, then how are we supposed to get the generator working with our existing redux setup? Well, to be able to use the generators, we’ll need to change few things:

Action Creator

We’ll need to change our action creators to accept page’s name:

The action creators generator for our common News action creators

Reducer

To transform our reducer into reusable reducers, first, we have to decouple the reducer and action handler:

Decoupled reducer and action handler

What we’re doing in the above codes are actually the same with using reducer in switch form, we’ll match the action’s type with Action Handler object keys(in switch, this is the case part), if it isn’t found, then we simply returns the current state (in switch, this is the default part).

Finally after these two had been decoupled, we’ll implement them to use our reducer generator function:

Implement the generator function

Using the common redux logics

To use the common redux logics, we can simply call our generator functions, that’s it:

Voila! reusable redux, like a boss!

The Selectors

Common redux logics like above works well with Redux Selector pattern. In Redux Selector pattern, a selector function receives the whole redux state tree and slice or compute derived data from it to obtain data that is currently requested. In React and Redux setup, usually we’ll implement this pattern with the help of reselect library.

For this example, let’s pretend that we’ve just received a word from our product manager that he wants to separate the news section in Home page into different sections with the following requirements:

  1. Editor’s Choice — We want this section to be filled with 6 latest featured news.
  2. Other News — This section will contains the other news that didn’t make it to the top 6.

Instead of t̵h̵r̵e̵a̵t̵e̵n̵i̵n̵g̵ ̵a̵n̵d̵ ̵d̵e̵b̵a̵t̵i̵n̵g̵ asking our Back-end engineers to change their API response schema, we might be able to solve this problem with the help of selectors. First, we’ll create a selector for our common news redux:

The news redux secret selector recipes are safe within their own scope

With above selector, we can abstract the implementation detail on how to select specific data from news redux state to its own selector. Then in our Home page, we can simply compose our Home selectors to use the news selector implementation to compute its derived data:

Home selector asked news selector to give away its data without the need to know their secret recipes, everyone is happy!

With this pattern, if there’s any data structure or implementation detail changes, we’ll only need to change how we select our news data in news selector, if we need to change how we compute our data in Home page, then we’ll simply change how we select the data in our home selector, Simple!

Using Selectors in React Component

The last thing we need to do is to use our selectors on mapStateToProps function in our React Component:

Love selectors much?

Well, that’s all you need to reuse your Redux logics.

Happy Hacking! — And don’t forget to check the DEMO to better grasp the concept.

--

--