Before you go, check out these stories!

0
Hackernoon logoRedux-saga pattern: flow sagas and common sagas by@cvarisco

Redux-saga pattern: flow sagas and common sagas

Author profile picture

@cvariscoChristian Varisco

I’ve been working with redux-saga for half a year and I love it because it allows to write clean declarative code.

Every time that I approach a technology I research patterns, conventions, best practices to improve my knowledge of it.
I found a lot of resources (documentation is very good) on redux-saga but nothing that explains how to structure and define sagas on the application to be more maintainable and scalable.

Considering that, I would like to share how I manage sagas hoping that this article can help someone and receive some feedbacks to improve.
 The simple concept is to define two kind of sagas, flow and common.

What are flow sagas and common sagas ?

Common sagas:

are sagas that have only one responsibility and could be used from all part of our application.
They should include every time the actions lifecycle (START, SUCCESS, FAILURE)
They should return always something and to be called they should be exported as generators.
They delegate the error management to the flow sagas.
The actions dispatched from here can manage the state of the redux store.

Example: Get the preferences of the user.

Flow sagas:

are sagas that manage the behaviour of a feature and should be used only by one feature.
We can also define a flow saga, a saga that creates a behaviour using common sagas.
They’re always invoked by a dispatched action and describe the behaviour (flow) of a specific feature.
They should manage the success and the failure behaviour, for which we use the TRY-CATCH statement.
Inside the try we have the success behaviour and inside the catch the failure one.

Example: How the feature works on the bootstrap.

Why I like it ?

  • Creating a difference between sagas helps you to make your application easier to maintain because you can reuse the common parts and split the responsibilities of your business logic.
  • By splitting the two kinds of sagas you can change your application very fast, because in this way you can isolate behaviours and change them without touching anything else.
  • Error handling is very easy because you have only one place where you handle it.
  • You can know what happens in your application because actions logging is very clean and find bugs will be rewarding!

I hope that this article can help you to avoid some of the problems I encountered.
I’m curious on what is your approach, and what do you think about the article.

Have fun coding 🚀

Follow me on Github: https://github.com/CVarisco
Follow me on Twitter: https://twitter.com/chrivarisco

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!