When should I be using Redux Sagas? [closed]
Asked Answered
S

3

6

I'm still fairly new to Redux and have not used Redux Sagas, so I'm unsure whats a good situation to start using Sagas. Or other solutions.

The current use case is: I have a Redux action that calls a web API and, after getting the results back, may need to fetch data from an additional 1-20 APIs.

What are the use cases for sagas? What are the alternatives? How should i start with this code.

Stakeout answered 17/4, 2018 at 14:34 Comment(2)
No, you don't need them, start with simpler solutions.Decadence
This post anwers the question well: #72360831Amputee
X
4

The majority of projects use Redux Thunk to organize side effects. In principle, it gives a good result: it’s easy to read and test the code (but you still need to mock network requests). But it all is fair as far as the logic of your action creators (or thunks) is simple. Unfortunately, for more than a few functions the code becomes harder to read, which makes it even more difficult to test.

In this situation, Redux Saga comes to the rescue. Redux Saga is an alternative approach to the organization of side effects. Instead of dispatching functions processed by Redux Thunk you create saga and write all the logic of event stream processing. Unlike thunks that are carried out when you dispatch them, sagas run in the background right after the app is launched. Sagas observe all actions that the store dispatches and decide what to do with them.

At this point, we can allocate three key benefits of sagas:

  • Simplicity in organizing difficult side effects sequences;
  • Declarative style;
  • The simplicity of testing.

If you want to know how to put saga into practice, check our article: https://blog.s-pro.io/use-redux-saga/ where you'll find code examples and much more!

Xuthus answered 13/12, 2018 at 14:31 Comment(0)
I
2

You might want to check out Redux Thunk. It's a very sensible and easy to understand approach to async Redux actions.

Islek answered 17/4, 2018 at 14:37 Comment(0)
S
1

Compared to redux thunks sagas give you some advantages like:

  • Ability to wait for actions - (good for: better decoupling of your modules, writing complex async flows, having all your actions logged via redux logger, ...)
  • Easier testability
  • Writing async. code like synchronous (same as async/await but with currently better browser support)
  • Task canceling (native promises don't support canceling)

If you don't find yourself particularly needing any of that it will be probably easier to just use thunks with possibly some promise library like bluebird.

That said Redux Sagas are great, but if you are just starting to use redux it might be better to stick to easier solutions first and once you feel comfortable start exploring libraries like redux sagas.

Swashbuckling answered 17/4, 2018 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.