Redux-Thunk and Redux-Saga both are middlewares of redux to handle asynchronous tasks. But wait, what are middlewares in redux? So, Redux-Middleware is a function or a piece of code that sits between action and reducer and can interact with the dispatched action before reaching the reducer function. A redux middleware can be used for many purposes such as logging (e.g. redux-logger), asynchronous API calls and so on. Let’s understand middleware with an example: Suppose a user clicks on a button and an action is dispatched then that action goes first to middleware instead of directly going to reducer. Once middleware is done with that action, then that action goes to reducer. Simple.
What is redux-thunk?
A thunk is a function that acts as a wrapper in that it wraps an expression to delay its evaluation. Thunk is redux middleware. It is used to handle async task or api call in redux.
What is redux-saga?
Redux Saga is also a middleware library that helps us with API calls or side effects. Redux Saga uses an ES6 feature called ‘Generators’ which helps us to write asynchronous code. Generators are the functions that came with ECMA Script 6. And the amazing part is that the generator functions can be paused in between the execution or even can be exited and later re-entered.A generator function is represented as: function* functionName() {}
Let’s see some difference between Thunk and Saga:
So, when to use redux-thunk or redux-saga if they both are used to handle asynchronous task?
Both packages are greate in handling asynchronous tasks. You can use either of them in you project or you can use both in same project.
Use redux-saga if :
Use redux-thunk if:
This is where we share our knowledge and insights. Our aim is to impart industry insights to help our website visitors take away valuable information.
Explore More Blog ⟶