redux-toolbelt: Supercharge Your Redux

10x less code, 10x more redux power - part 2 - the basics

Vitali Zaidman
Feb 3, 2018 · 4 min read

In the first article, we introduced redux-toolbelt in general.

In this article we will show the strength of redux-toolbelt and what it can do for you and look at the API of redux-toolbelt and how to use it.

Example

Before we dive into the features of redux-toolbelt, here is a short example of vanilla Redux code converted to redux-toolbelt .

The following vanilla Redux code consists of one action and a reducer that handles it:

The vanilla Redux way.

Now lets convert it to the equivalent code in redux-toolbelt:

The equivalent redux-toolbelt way.

Live Sandbox

A live sandbox of the demonstration is available here So you can play around with redux-toolbelt while reading this article.

And here is The github repository of the demonstration.


Lets dive into the code now:

makeActionCreator

documentation, usage

Creating actions via redux-toolbelt is much simpler and shorter.

First, lets look on how action creators are created in vanilla Redux:

Actions in vanilla Redux.

Now, lets create the same action creators using redux-toolbelt:

Creating simple actions with redux-toolbelt.

That’s it, with a line of code, your action creator is ready for use.

You don’t have to save the action’s names in a separate constants file, instead the name of the actions is saved on the created toolbelt action creator itself.

When you execute the action creator, the action creator’s payload and metadata are passed as the action’s first and second arguments.

Executing action creators.

Now, instead of importing action types from a constants file in the reducer, we now import the action creators directly. actions type will be found on the TYPE property of every action creator.

makeReducer

documentation, usage

makeReducer creates a simple reducer to handle action creators that were created using makeActionCreator.

For example, lets create an action creator:

Then lets import the newly created action creator and create a reducer to handle it:

makeReducer accepts 3 arguments: action creator, action handler, options.

In the example above we use defaultState to ensure the initial state of countReducer is 100.

Now lets take a look at countReducer and see how handles increaseBy dispatches:

Async Support

redux-toolbelt’s asynchronous actions and reducers creators simplifies and shortens the code and boilerplate required to implement common async redux scenarios.

makeAsyncActionCreator

documentation, usage

makeActionCreator creates, in one line of code, multiple actions that represent the different stages of an async process.

It is all the more useful in async/side effects middlewares like redux-thunk, redux-saga or redux-observable.

Let’s see an example of how the it is created and used:

Creation of an async action creator.

As you can see, the redux-toolbelt’s async action creator holds sub actions for each step in the asynchronous process lifecycle (request, success, failure, progress and cancel).

We can now import the action creator directly to reducers.js to get it’s different action types.

Simple handling of an async action creator in a reducer.

As opposed to what you just saw, in vanilla Redux, every action is verbosely defined by it’s own and their only connection is by convention.

And now… The magic begins:

makeAsyncReducer

documentation, usage

Creates a reducer that handles async action creators we discussed in the last section with makeAsyncActionCreator.

Lets see an example:

Creating a redux-toolbelt async reducer.

The last line of code creates the same reducer like the one we saw in the previous example, that handles all the actions that are omitted during the fetch profile asynchronous process:

The makeAsyncReducer function creates a reducer equivalent to this one, with one line of code.

In redux toolbelt all the life cycle of an asynchronous process in defined using one async action creator, and handled using (usually one) async reducer.

The makeAsyncReducer options configure the reducer for more advanced scenarios.

makeAsyncReducer with the defaultData and dataGetter configs.

Using another set of options, we spread the results of the process on success and do not destroy data on process start:

makeThunkAsyncActionCreator

documentation, usage

While makeAsyncActionCreator is great, makeThunkAsyncActionCreator makes it awesome.

Using makeThunkAsyncActionCreator

It creates an async action creator from a promise, so with a line of code you get the fetchTodosFromServer ready to be executed when the fetchTodos action is called and fetchTodosFromServer.success and fetchTodosFromServer.failure executed upon promise resolving.

composeReducers

documentation, usage

Currently the holy grail of the library. It helps us in many cases and best used in a combination with the functions described before.

composeReducers runs its reducers one by one, top to bottom. If an argument is an object it combines them.

So in the following example, a reducer that handles logging out, runs after the three combined reducers profile, customers and orders and resets all the three states.

Again, the initial state the reducer produces is:

After login and all data fetching:

And when the user clicks on logout all the states are reset to data: null.

This demonstrates how composeReducers helps you to easily affect several states at once.

Conclusion

redux-toolbelt provides us with a fast and easy way to create actions and reducers that follow the most commonly used patterns in redux.

It also provides us with a way to work on a combination of states that each of them has it’s own reducer.

Also, in the next parts we will discuss how redux-toolbelt-immutable-helpers, redux-toolbelt-observable, redux-toolbelt-saga can improve your life even more.

Happy Reduxing :)

Welldone Software

The leading full-stack consultancy. Creating amazing frontends and rock-solid backends using top notch technologies and practices. Visit us at https://welldone.software.

Thanks to Dori Frost

Vitali Zaidman

Written by

https://twitter.com/vzaidman ⎝(•ω•)⎠ https://vzaidman.com

Welldone Software

The leading full-stack consultancy. Creating amazing frontends and rock-solid backends using top notch technologies and practices. Visit us at https://welldone.software.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade