When should I use Redux Saga instead of Redux Thunk, and when should I use Redux Thunk instead of Redux Saga?
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)
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
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