A deep dive into why I use Redux-Saga

In my previous blog post, I went over my current software development tool-belt, I revealed what is in my tool-belt and why I use it. One of those packages in my tool-belt is Redux-Saga.

What is Redux-Saga?
Redux-saga is a redux middleware library, that is designed to make handling side effects in redux.

As I said before they were introduced to me by Mateusz Bosek, and he liked them. Moreover, since I began using sagas, I’ve also grown to love them and the redux-saga pattern.

React, Redux and Redux Saga.

The Redux-Saga Pattern
Redux-Saga leverages Generators, allowing us to write asynchronous code that looks synchronous, and it is easily testable – This right here is what makes redux-saga powerful, and this is why I love the redux-saga pattern.

For example, let says you have a user login process which does the following:

  • Get the username and password from state
  • Call login API endpoint with the username and password – on success get the user authorisation token
  • Save auth token in the store
  • Remove the username and password from the store
  • Call Settings API endpoint with the authorisation token – on success get the user settings
  • Set the user settings in store

This is what the saga looks like for the user login process:

In this example above I’ve used what redux-saga calls Effects, these Effects are:

  • select: Used to select state from redux store (same as getState())
  • call: Used to call other methods with arguments
  • put: Dispatches action

So my userLoginSaga is okay. However, It needs some refactoring.

So my userLoginSagaRefactor is much better. The API calls now have their own sagas. Additionally, this version is much better for unit testing. In the unit test I can test each yield, like the following:

This unit test will check each yield. The order is essential, otherwise, the test will fail. There are other forms of testing redux-saga for example redux-saga-test-plan

Conclusion
I am forever grateful to Mateusz Bosek for introducing me to redux-saga. It’s made the applications I work on better and improved my coding experience.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.