Our Tech Journal
  • Introduction
  • Overview
    • Introduction
  • Javascript
    • JS Runtime, Env Context, Scopes, Hoisting & Execution Cycle, var/let/const, this
    • Javascript Runtime Env
      • Event loops
    • What are WebVitals
    • Module Patterns in JS - CommonJS, AMD and ES6 classes
    • Lexical Environment in JS
    • var vs let/const
    • Temporal Dead Zone (TDZ)
    • Execution Context
    • 'this' keyword
    • undefined value in JS
    • Function expressions vs Function statements
    • Javascript Code Execution
    • Closures
    • JS : Object Oriented Programming
    • Prototypal Inheritance
      • Creating Object in Javascript
    • NaN
    • Objects
      • Ways to create
      • ways to check if Object is empty
      • Object's own properties
    • use strict mode
    • typeof vs instanceof
    • Promise
    • localStorage and SessionStorage
    • Event handlers
    • Event bubbling
    • Event Delegation
    • XHR Request
    • Promise Error: Catch vs Error Function in Then
    • Immutability
    • Useful Code samples
    • window, document, screen
    • window.innerheight, outer height, screen.height
    • JS Design Patters
    • Interview Questions
    • Encapsulation - Module Patterns in JS
    • Redesigning services using Entity framework approach
  • JS Functions
    • JS Array - Slice vs Splice
  • PWA
    • What is PWA
  • ES6
    • Sets
    • Maps
    • spread vs destructure operator
  • Web
    • http / https
    • CORS
    • CSRF
    • XSS Attack
    • What is SPA
    • Semantic Elements in HTML
  • Angular 4
    • Angular vs React
    • Change Detection
    • Lazy Loading of modules
    • Preloading
    • AOT Compilation
    • Route Guards
    • Shared Modules
    • Tree Shaking
    • LifeCycle Hooks
    • ngRx
    • Observables
    • Observable vs Subject
      • BehaviorSubject
    • Observables vs Promises
    • Builtin Directives
      • Temp
      • Structural Directives
        • ngForTemp
        • ngSwitch
        • ngFor
        • ngIf
      • Attribute Directives
        • temp
        • ngClass
        • ngStyle
    • Routing
      • Routing in Angular
      • Setting up basic routing
      • routerLink and routerLinkActive
      • router.navigate and ActivatedRoute
      • Route Params as Observables
      • redirectTo
      • relativeTo
      • pathMatch
      • ActivatedRoute
      • Routing in Angular
      • Passing Data with Route
      • Route Parameters
    • Intercept HTTP request
    • Custom Directives
    • Communication between components
    • Angular Modules
    • Reactive Forms
    • Unit Testing
      • TestBed and component fixture
      • Testing HttpClient requests
      • Testing fakeAsync
  • GraphQL
    • Introduction
    • Server
    • Client Side
    • GraphQL in Angular
    • Queries
      • temp
      • query with parameters
      • aliases
      • fragments
      • @include directive
      • @skip directive
      • variables
      • Inline Fragments
  • CSS
    • What is Box model?
    • display: block, inline or inline-block
    • CSS Selector: Combinators
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS3 Filter
    • CSS3 Transitions
    • Media Queries
    • Flex vs Grid
    • CSS 3 Grids
    • What is Flexbox?
    • position: relative vs absolute
  • SASS
    • Mixins
    • Lists
    • Maps
  • RxJS
    • throttle vs debounceTime
    • distinctUnitChange
    • reduce vs scan
  • Typescript
    • Typeguards
    • Pattern Matching with Typescript
    • TS Decorators
    • Using LINQ in TS
  • NodeJS
    • NodeJS Security Checklist
    • What is Node.js
  • REACT
    • React - VDOM - Under the hood
    • Synthetic events in React
    • Routing - React Router 4
    • React Custom hook
    • Higher-Order Component
    • REDUX
    • Redux Thunk vs Redux Saga
    • forceUpdate()
    • Storing Data in React
    • Error Handling
    • React Context
    • How React-Native works
    • refs
    • Server-side Rendering
    • Jest setup file
    • React-test-renderer
    • Lifecycle
    • React Testing Library
    • React Query
  • JWT
    • What is JWT and How it works
Powered by GitBook
On this page
  1. REACT

Redux Thunk vs Redux Saga

PreviousREDUXNextforceUpdate()

Last updated 2 years ago

Why Redux?

  • Redux is an open-source, cross-platform library for managing the application state

  • While redux is widely used with React & React Native, its usage is not limited to these technologies

  • It is an independent tool that can be plugged in with any UI layer or framework such as Angular, Vue, Ember, Flutter or even Vanilla JS

Redux to Your Rescue

Passing or sharing data from one component to other is a major task and can sometimes be very frustrating. To help us with situations like these, Redux offers immense help. Redux keeps a single store (sometimes called as the ‘Single source of truth’ of all your application state(data) and the components can connect to the redux store and get back the data they want.

Data Flow in Redux

Redux follows a unidirectional data flow. Redux has 3 major components: ‘actions’, ‘reducers’ and the ‘store’.

Actions are simple JavaScript objects. It has a ‘type’ property which specifies the type of the action we are performing and optionally, can also have a ‘payload’ property which is used to send some data to our redux store.

A simple action object can be as follows:

Reducers are the functions that determine the changes in application state and return the updated state. They take actions as the argument and update the state inside the store.

Sample reducer will look like this:

What is a Redux middleware?

Redux middleware = 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.

Image: Redux Thunk vs Redux Saga

What is Redux Thunk ?

Redux and stuff is fine. What is “Thunk” anyway?

The word “Thunk” may seem vague at first but to put in amazingly simple terms, Thunk is just a function returned from another function.

Let us see an example:

Redux Thunk is a middleware that allows you to call the action creators that return a function(thunk) which takes the store’s dispatch method as the argument and which is afterwards used to dispatch the synchronous action after the API or side effects has been finished.

In the above example, getCartItems() is an action creator which returns a function which in turn takes dispatch method as the argument. After we have received the cartItems from the server, we will dispatch a regular synchronous action using the dispatch method.

I hope this makes sense now.

Now that we have seen what Redux Thunk helps us with, let us now see what Redux Saga offers us.

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() {}

A simple example of generator function can be:

Calling a generator function does not execute it at once; instead, it returns an iterator object. When we call the next() method on iterator object, function body is executed until it sees the next “yield” keyword.

next() method returns an object with a “value” property which has the value that has been returned by yield and a “done” property which stands for whether a function has completed execution or not.

How does Redux Saga work?

Redux Saga listens to the dispatched actions and triggers an API call or any other side effect you write.

Let us see in an example for how we can call an API endpoint using Redux Saga.

Saga works like a separate thread or a background process that is solely responsible for making your side effects or API calls unlike redux-thunk, which uses callbacks which may lead to situations like ‘callback hell’ in some cases. However, with the async/await system, this problem can be minimized in redux-thunk.

Who Wins?

It is completely up to you to choose the right approach for your projects. Personally, I have used both Redux-Thunk and Redux-Saga, and I feel if you are working on a small or a medium scale project, you can choose Redux-Thunk. It will work like a charm. But on the other hand, for bigger projects, Redux-Thunk may sometimes get you in trouble, as it can be hard to scale if your side effect or asynchronous logic increases, whereas in case of Redux-Saga, it comes power packed with some amazing things such as concurrent side effects, cancelling side effects, debouncing and is easy to scale.

To be honest, I love both tools. Choosing one is difficult as both have its advantages and disadvantages.

Redux-Thunk
Redux-Saga

Less boilerplate code

More boilerplate code

Easy to understand as compared to redux-saga

Difficult to understand as there are multiple concepts to learn like generator functions and redux-saga effects

May be difficult to scale up

Easy to scale as compared to redux-thunk

Action creators may hold too much async logic

Action creators stay pure

May get difficult to test

Comparatively easy to test as all your async logic remains together

Confused? Let us see an example:

Do not Sweat. This is not a Pointer.

https://www.eternussolutions.com/2020/12/21/redux-thunk-redux-saga/
😧
😧
😧
😰