Banner Image

Redux Thunk vs Redux Saga

Shivam
November 26, 2021
1 Minute Read

scroll

down

Banner Image

Looking for other services or solutions?

ux/ui image
Explore our services

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.

See the source image

 

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:

Thunk vs 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 :

  • You want to scale up your project.
  • You want to test your project.
  • You want to handle websockets in your project.
  • Your project is big.

Use redux-thunk if:

  • Scalling is not concern.
  • Testing is not necessary.
  • Project is not a big project.
  • You dont want to write alot of boilerplate code.
0 Shares
Tweet
Share
Share
Pin