Redux Middleware- The differences between Redux-thunk and Redux-saga

Introduction
In redux, we always need middleware to help us to handle the asynchronous operations or other side effects.
The most popular middlewares are Redux-thunk and Redux-saga.

This topic notes the differences between Redux-thunk and Redux-saga for using. We will discuss the following items.
- Overview
- Concepts
- Roles and usages
- Libraries
- Implementations
Overview
Definitions
- Redux-thunk (the definitions from npmjs.com)
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.
- Redux-saga (the definitions from redux-saga.js.org)
redux-sagais a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.
File structures
The following figure is the figure I made for learning the Redux-thunk and Redux-saga. We can discover a few different things for their structure.

Concepts
What is a thunk?
A thunk is a function that wraps an expression to delay its evaluation.
// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2;// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2;Concepts of Redux-thunk middleware
- Check if the action is a pure object or a thunk
- Pass the action to the next middleware if it’s a pure object
- Launch the action if it’s a thunk
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => (next) => (action) => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}const thunk = createThunkMiddleware();thunk.withExtraArgument = createThunkMiddleware; export default thunk;Roles and usages
I refer to Redux Saga with React: Fast-track Redux Saga intro course for the example and the source code for the Redux-saga part.
Reducers
- Reducer decide which state to change depends on the type of actions
- For Redux-thunk, we usually have one state for a request(start)
- For Redux-saga, we need two states for a request(start and success)

Actions
- Redux’s actions are exposed functions
- For Redux-thunk, the exposed functions call dispatch to change global states
- For Redux-saga, the exposed functions only return JSON

Store
- For Redux-thunk, we have to create an initial state and integrate it with thunk in the store.
- For Redux-saga, we have to create sagas with generator functions and integrate them with the saga middleware in the store.

Sagas (Only React-saga needs)
- For Redux-saga, we have to create generator functions such as watcher and fetch resources here.




