What is the difference between Redux Thunk and Redux Saga? - reactjs

Both Redux Thunk and Redux Saga are middleware of Redux. What is the difference between two and how to determine when to use Redux Thunk or Redux Saga?

Both Redux Thunk and Redux Saga take care of dealing with side effects.
In very simple terms, applied to the most common scenario (async functions, specifically AJAX calls) Thunk allows Promises to deal with them, Saga uses Generators.
Thunk is simple to use and Promises are familiar to many developers, Saga/Generators are more powerful but you will need to learn them.
When Promises are just good enough, so is Thunk, when you deal with more complex cases on a regular basis, Saga gives you better tools.
As an example, what happens when you start an AJAX call in a route/view and then the user moves to a different one? Can you safely let the reducer change the state anyway? Saga makes it trivial to cancel the effect, Thunk requires you to take care of it, with solutions that don't scale as nicely.
In practical terms choosing one or the other one really depends (tautologically) on the project.
One thing to keep in mind is that the two middlewares can coexist, so you can start with Thunks and introduce Sagas when/if you need them (and then choose how/what to refactor with hands on experience... A solution that especially fits "learning projects", MVPs, et similia)
In general terms, Sagas are more powerful and easier to test, but they introduce many new concepts, that can be a bit overwhelming if you're also learning other technologies (Redux especially).
Specifically, while dealing with the simple and effective Redux philosophy (actions (literal objects) fed into reducers (pure functions)), you can deal with side effects with Thunk that is more limited but easy to grasp (Promise.then().error()), or with Saga that requires you to face the (powerful) notion that you can do more complex things with those actions.
It's also worth mentioning (redux-)observable has an even more complex (and even more powerful) paradigm to deal with side effects, just in case you are unfamiliar with it (if you already are, it might be easier to use than learning Saga).

Actually, Both of them are middleware for Redux to deal with asynchronous actions. For knowing the difference between then please pay attention to the following picture:
The middleware box generally refers to software services that glue together separate features in existing software. For Redux, middleware provides a third-party extension point between dispatching an action and handing the action off to the reducer. then reducer makes the new state.
Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed. simple, easy to learn and use with 352B volume
Redux Saga leverages an ES6 feature called Generators, allowing us to write asynchronous code that looks synchronous, and is very easy to test. In the saga, we can test our asynchronous flows easily and our actions stay pure. complicated, hard to learn and understand, 14kB volume but organized complicated asynchronous actions easily and make then very readable and the saga has many useful tools to deal with asynchronous actions
HINT: If you cannot understand the difference between them or understand the redux-saga flow but still you wanna have readable code and avoid callback hell, go after redux-thunk by using async/await, I leave an example for offer:
// simple usage of redux-thunk:
export const asyncApiCall = values => {
return dispatch => {
return axios.get(url)
.then(response =>{
dispatch(successHandle(response));
})
.catch(error => {
dispatch(errorHandle(error));
});
};
};
// async/await usage of redux-thunk:
export const asyncApiCall = values => {
return async dispatch => {
try {
const response = await axios.get(url);
dispatch(successHandle(response));
}
catch(error) {
dispatch(errorHandle(error));
}
};
};

Related

What is the difference between using redux-thunk and calling dispatch() directly

I'm in the learning phase of understanding redux state management and still trying to negotiate the bewildering jungle of boilerplate code and middleware, much of which I'm taking on faith as 'good medicine'. So I hope you'll bear with me on this perhaps rudimentary question.
I know that redux-thunk allows action creators to proceed asynchronously and dispatch a regular action at a subsequent time. For example, I can define a thunk action creator in my actions.js:
export function startTracking() {
return (dispatch => {
someAsyncFunction().then(result => dispatch({
type: types.SET_TRACKING,
location: result
}))
})
}
And invoke it from within a React component like so:
onPress={() => this.props.dispatch(actions.startTracking())}
My question is, what advantage does the above code confer over simply dispatching an action from inside an asynchronous callback?
import { store } from '../setupRedux'
...
export function startTracking() {
someAsyncFunction().then(result => {
store.dispatch({
type: types.SET_TRACKING,
location: result
})
})
}
which I would invoke inside my component
onPress={() => actions.startTracking()}
or even
onPress={actions.startTracking}
Is there anything problematic with accessing store directly via an import as I'm doing in the 2nd example?
There is nothing wrong doing so. From the redux-thunk page:
If you’re not sure whether you need it, you probably don’t.
The creator of redux explain the advantage of using it here:
This looks simpler but we don’t recommend this approach. The main reason we dislike it is because it forces store to be a singleton. This makes it very hard to implement server rendering. On the server, you will want each request to have its own store, so that different users get different preloaded data.
Basically, using redux-thunk will save you the store import in each action creator file and you will be able to have multiple store. This approach also give you the opportunity to write a little bit less code and to avoid spaghetti code. Many redux developer don't like to import the store and to manually dispatch because it can create circular dependencies if the code is badly separated (importing an action name from the action creator file in the reducers file and importing the store from the reducers file in the action creator file). Also, dispatching directly an action like that might break the middleware workflow, ie: the action might not be handled by a middleware.
But honestly, if you don't see an advantage to it yet, don't use it. If one day you have trouble with async actions, redux-thunk might be the answer.

Are there any patterns for decoupling coupled async data in redux saga?

I have two container(connected to a redux store) components(say A and B) on a page that both depend on one redux saga to complete for their data.
Currently what I'm doing to avoid two async calls(and to avoid one making the call and have the other check for the data to be there) is to move the async call up into a higher container component C that contains both A and B.
Then I'm converting A and B into normal components(not connected to the store) and passing them props from C.
Is there a pattern out there to achieve this better?
or any migration path to achieve this conversion?
or is it best just to do this change and spend the time moving the async call up to C and convert A and B to standard components?
Is there a pattern out there to achieve this better?
Best practice to prepare data into multiple components and handle their actions is having one root redux-provider, which provides all actions and store connection to descending components.
Then, redux-saga can intercept any actions and perform API call, since it combination of middleware and process manager. Usually components dispatch only _REQUEST-like action, after receiving which saga performs batch of async operations and then put _SUCCESS of _FAILURE-like action to reducers.
Of course, if you want to support optimistical update, _REQUEST-like action should be also supported in reducers.
If your components has explicit or implicit link between them, simple action handling via takeEvery or takeLatest can be not enough. But saga simply allows to perform creating multiple async processes, which can accumulate state in local closure before yield-based loop.
function * manyActionsSaga() {
let flowPromise = Promise.resolve();
while(true) {
const action = yield take(['ACTION_1', 'ACTION_2', 'ACTION_3']);
yield call(() => flowPromise)
flowPromise = flowPromise.then(() => {
// Similar event handling
})
}
}

Can I make store update thenable in react redux app?

I'm in a problem when update store of my react redux app.
How can I make store update thenable?
As you know, all updates of states are async, so we have to use componentDidUpdate method if I do something as a callback function of state update. But these are sometimes complicated. I'd like to make this simple, by something like making them thenable method. Does have any body any idea?
The reducer function supposed to be pure so the async logic should not be there.
There are few middlewares you might be interested in:
redux-thunk allows you to have action creator that returns a function which dispatch and getState from store are injected into a normal action which means can delay the dispatch however you want. But it has limited power. (which you might not need more than that)
redux-saga use generators to explain all the side-effects and async operation in terms of data. It is more powerful than thunk, you can do complicated async interaction, for example, racing between multiple actions. But the downside is there will be more action you need to create and unpredictability caused by action dependencies.
redux-observable is claimed to be more sophisticated than saga. It is based on Rx observable stream and you can manipulate stream of actions with map flatMap filter which similar to array's method but there are more you can use. For me, it's interface looks much nicer than saga. Some might argue against the learning curve needed for understanding Rx.

How to dispatch multiple actions one after another

In my react / redux application I often want to dispatch multiple actions after another.
Given the following example: After a successful login I want to store the user data and after that I want to initiate another async action that loads application configuration from the server.
I know that I can use redux-thunkto build an action creator like this
function loginRequestSuccess(data) {
return function(dispatch) {
dispatch(saveUserData(data.user))
dispatch(loadConfig())
}
}
So my questions are:
When the first dispatchreturns, is the state already changed by all reducers listening for that action? I'm wondering if the two dispatch calls are run strictly sequential.
Is this approach considered best practice for dispatching multiple actions? If not, what would you suggest alternatively?
Thanks for any help!
Yes redux-thunk allows you to do as you say, and yes it is a best practice for dispatching multiple actions (one that I prefer over the alternatives because of it's simplicity). The state is indeed updated as soon as you dispatch (by the time it returns), which is why you are given a function to retrieve the state in a thunk, instead of simply a reference to the state. In that way you can alter the state with one dispatch, and then call getState() to get a reference to the new state to read from if you need to.
redux-thunk is exactly what you are looking for. I consider it very good practice.
To answer your question, indeed when the first dispatch returns the state is already changed by the called reducers.
I know its a late response :-P You can do this by using Redux-Thunk and also checkout Redux-Saga. Redux Saga provides an amazing way to handle loads of actions at the same time. Below is an example of dispatching multiple actions using Redux-Thunk
function getAndLoadSider(moduleName){
return function(dispatch){
return doSomeApiCall(someData).then(function(item){
let _item = someOtherFunction(item.collections);
let _menuData = {
name: item.name,
key: item.key
};
return new Promise(function(res, rej){
dispatch(actionOne(_menuData));
res(_item);
}).then((_item) => dispatch(actionTwo(_item)))
}
}
Above method works well for your case when one action is dependent on the first. This is a promise based approach. If you don't like to do a lots of Promise coding I recommend you go for Sagas. Check out this link https://redux-saga.js.org/docs/advanced/ComposingSagas.html where you will learn how to compose sagas. Learning curve is steep; but once you are done, Sagas will make you a ninja redux dev.
Hope this helps :-)

What is the difference between redux-thunk and redux-promise?

As far as I know and correct me if I am wrong, redux-thunk is a middleware which helps us dispatch async function and debug values in the action itself while when I used redux-promise I couldn't create async functions without implementing my own mechanism as Action throws an exception of dispatching only plain objects.
What is the major differences between these two packages? Are there any benefits of using both the packages in a single page react app or sticking to redux-thunk would be enough?
redux-thunk allows your action creators to return a function :
function myAction(payload){
return function(dispatch){
// use dispatch as you please
}
}
redux-promise allows them to return a promise :
function myAction(payload){
return new Promise(function(resolve, reject){
resolve(someData); // redux-promise will dispatch someData
});
}
Both libraries are useful if you need to dispatch action async or conditionally. redux-thunk also allows you to dispatch several times within one action creator. Whether you choose one, the other or both entirely depends on your needs/style.
You'll likely want/need both together in your app. Start with redux-promise for routine promise-producing async tasks and then scale up to add Thunks (or Sagas, etc.) as complexity increases:
When life is simple, and you're just doing basic async work with creators that return a single promise, then redux-promise will improve your life and simplify that, quick and easy. (In a nutshell, instead of you needing to think about 'unwrapping' your promises when they resolve, then writing/dispatching the results, redux-promise(-middleware) takes care of all that boring stuff for you.)
But, life gets more complex when:
Maybe your action creator wants to produce several promises, which you want to dispatch as separate actions to separate reducers?
Or, you have some complex pre-processing and conditional logic to manage, before deciding how and where to dispatch the results?
In those cases, the benefit of redux-thunk is that it allows you to encapsulate complexity inside your action-creator.
But note that if your Thunk produces and dispatches promises, then you'll want to use both libraries together:
the Thunk would compose the original action(s) and dispatch them
redux-promise would then handle unwrapping at the reducer(s) the individual promise(s) generated by your Thunk, to avoid the boilerplate that entails. (You could instead do everything in Thunks, with promise.then(unwrapAndDispatchResult).catch(unwrapAndDispatchError)... but why would you?)
Another simple way to sum up the difference in use-cases: the beginning vs. the end of the Redux action cycle:
Thunks are for the beginning of your Redux flow: if you need to create a complex action, or encapsulate some gnarly action-creation
logic, keeping it out of your components, and definitely out of reducers.
redux-promise is for the end of
your flow, once everything has been boiled down to simple promises, and you just want to unwrap them and store their resolved/rejected value in the store
NOTES/REFS:
I find redux-promise-middleware to be a more complete and understandable implementation of the idea behind the original redux-promise. It's under active development, and is also nicely complemented by redux-promise-reducer.
there are additional similar middlewares available for composing/sequencing your complex actions: one very popular one is redux-saga, which is very similar to redux-thunk, but is based on the syntax of generator functions. Again, you'd likely use it in conjunction with redux-promise, because sagas produce promises you don't want to have to unwrap and process manually with tons of boilerplate...
Here's a great article directly comparing various async composition options, including thunk and redux-promise-middleware. (TL;DR: "Redux Promise Middleware reduces boilerplate pretty dramatically vs some of the other options" ... "I think I like Saga for more complex applications (read: "uses"), and Redux Promise Middleware for everything else.")
Note that there's an important case where you may think you need to dispatch multiple actions, but you really don't, and you can keep simple things simple. That's where you just want multiple reducers to react to a single async call, and you would be inclined to dispatch multiple actions to those multiple reducers. But, there's no reason at all why multiple reducers can't monitor a single action type. You'd simply want to make sure that your team knows you're using that convention, so they don't assume only a single reducer (with a related name) can handle a given action.
Full disclosure: I'm relatively new to Redux development and struggled with this question myself. I'll paraphrase the most succinct answer I found:
ReduxPromise returns a promise as the payload when an action is dispatched, and then the ReduxPromise middleware works to resolve that promise and pass the result to the reducer.
ReduxThunk, on the other hand, forces the action creator to hold off on actually dispatching the action object to the reducers until dispatch is called.
Here's a link to the tutorial where I found this info: https://blog.tighten.co/react-101-part-4-firebase.

Resources