Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Redux Saga instead of Redux Thunk, and when should I use Redux Thunk instead of Redux Saga?

The question is different from the past which is why. The question for this one is When. Since both are good frameworks by themselves the question is when should I use thunk than saga. Because one of my friend keeps insisting me to use saga in our app but no apparent reason why. Thanks ahead

like image 282
Bon Andre Opina Avatar asked Jan 22 '19 05:01

Bon Andre Opina


3 Answers

Based on some readings and my experience...

Use Thunk instead of Saga for simple and trivial tasks like:

  • AJAX calls
  • data polling and only if they are started directly by the user interaction.

Use Saga for

  • intertwined tasks, the login example of the docs is perfect
  • flows with a lot of steps and waitings for other conditions to happen ("finite-state machine" flows)
  • tasks that work in the background and proceed independently from the user interaction (or a mix of background/interactions)
like image 185
NoriSte Avatar answered Nov 16 '22 01:11

NoriSte


Preferring saga over thunk or the other way round lies depends on the task in hand. Both have their fair share of trade-offs.

Thunks dispatch a function that in turn dispatches an actions. So,

  • Pros: Simple code to maintain
  • Cons: Have to mock the async behavior of thunk in test cases which could get pretty clumsy
  • Implies: Suited for small, straight forward async parts of the application

Sagas use generator functions underneath so the function virtually pauses at an async action and resumes when it is resolved

  • Pros: Test cases become fair and straight without necessity to mock the async behavior
  • Cons: Brings in more complexity to the code
  • Implies: Suited for complex async parts of the application that requires complex unit test cases
like image 44
Akshay R Avatar answered Nov 16 '22 02:11

Akshay R


Both thunk are saga are used as middle ware for redux used usually for api hit. Thunk is very easy to used compared to saga, but saga has alot of benefits over thunk for example saga has effect takeLatest which would be effective if user is pressing button repeatedly, thunk would make api hit on every click but using saga effect only latest(one) api hit will be made. It also have other effect and there benefits but it has learning overhead

like image 36
Umair Farooq Avatar answered Nov 16 '22 01:11

Umair Farooq