Understand Redux Higher Order Reducers

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

Higher Order Reducers are simple reducer factories, that take a reducer as an argument and return a new reducer. In that new reducer, you can customize the behaviour of the original one which helps reducing the reducer logic.

In this lesson, we'll see how to reduce duplicated code by refactoring two different reducers into a higher order reducer.

Here we have a very simple component that shows a list of users and articles. It also shows a couple of buttons for adding a user and an article.

Those buttons call a redux action, which are these two here, that are passed as properties to the component, so we try these buttons. They add users incrementally, and articles.

If we take a look at the reducers, you see, for example, here in articles, we have an article reducer, and the same for user. They both are very similar, so we can refactor this in a higher order reducer. For that, let's go to the index.js file where we combine all the reducers and create the root reducer.

Here, let's create an add function, which is the higher order reducer. It has two parameters, the reducer that we are applying it to, and the section that will be user, or article, in this case.

A higher order reducer is just a function that returns a reducer, and a reducer takes a state and an action as their parameters. The idea of a higher order reducer is that by default, it bypasses the call to the reducer, passing the state and the action.

Before, we can perform the actions we want. For example, we can say if action.type is equal to add an section, then if this condition is met, we will return the new state just as we do in the articles and the users reducer.

Just like that, we have our higher order reducer implemented, and the cool thing is that they can be applied to the reducer you like to. Let's apply it, for example, to users, this part the users reducer, and user, in upper case, and the same for articles.

Just like this, we added the add functionality, and we can remove it now from the other two reducers. If we try this again, we'll see it's working just as before.

Since higher order reducers are just normal functions, you can compose them or do whatever you want with them. For example, we can go deeper, and instead of using a string here, we can use a predicate.

Let's say we have a function that takes the action type, and if the action type includes add user, then that will pass, and we can do the same with the article one, add article. Then we receive a predicate, and we call the predicate passing the action type.

This should be working exactly the same. Even though it seems a bit more code, it's more flexible than the previous solution. This works as we expect.