Moving from redux-thunk to redux-saga

Written by salujaharkirat | Published 2017/10/28
Tech Story Tags: redux | redux-saga | redux-thunk | react | react-redux

TLDRvia the TL;DR App

I was working on a React, Redux project which involved lots of REST API calls, and I decided to use redux-thunk to handle that. The library no doubt is really amazing but there lot of boiler plate(redundant) code with all those dispatches and all which really increases the size of the project and with increase in complexity it really becomes hard to tackle and manage

My project is growing at really pace and I can see code getting more redundant with more and more usage of redux-thunk. So I decided to try redux-saga over this weekend and I am pretty amazed by the results.

First, to understand redux-saga you need to understand how Generators work in Javascript. I had used them earlier in python so I was aware of how they work but if you don’t have any idea of generators, do them out from here and then proceed. Without a good understanding of generators you won’t get how redux-saga works.

To compare redux-thunk and redux-saga, I decided to create a small project which fetches a data from a remote API, updates the local store and my component reads from that store and shows it on the page. Being a star-wars fan I used the open API of star wars as the end point.

Now coming to the project, we need to create to create actions, reducers and store for both redux-thunk and redux-saga. So in terms of configuration, pretty much entire code is same. Just the action part in redux-saga becomes really simple when generators kick in making redundant code of dispatches obsolete.

Here are the actions from both redux-thunk and redux-saga:-

Now if you see we are able to pass the promises to redux-saga middleware and it handles it automatically. This is something I was looking forward to because it does not involved dispatch and redundancy of code goes down drastically.

You can check the code for redux-thunk and redux-saga with these links:-

  1. redux-thunk — https://github.com/jinxac/redux-thunk-saga/tree/ba7e60bdfe1a5e689de117ed095782ec22ff322d
  2. redux-saga — https://github.com/jinxac/redux-thunk-saga/tree/6d85f28a41af2cef1c9af6da259b88962a082bb5

I am really convinced that redux-saga is better way of handling REST calls in react project if your project is about to scale or already at that level. I am planning to move my projects from redux-thunk to redux-saga.

If you liked the article you can follow me at github /twitter.


Published by HackerNoon on 2017/10/28