There is a lot of talk about the latest kid in redux town right now, redux-saga/redux-saga. It uses generator functions for listening to/dispatching actions.
Before I wrap my head around it, I would like to know the pros/cons of using redux-saga
instead of the approach below where I'm using redux-thunk
with async/await.
A component might look like this, dispatch actions like usual.
import { login } from 'redux/auth';
class LoginForm extends Component {
onClick(e) {
e.preventDefault();
const { user, pass } = this.refs;
this.props.dispatch(login(user.value, pass.value));
}
render() {
return (<div>
<input type="text" ref="user" />
<input type="password" ref="pass" />
<button onClick={::this.onClick}>Sign In</button>
</div>);
}
}
export default connect((state) => ({}))(LoginForm);
Then my actions look something like this:
// auth.js
import request from 'axios';
import { loadUserData } from './user';
// define constants
// define initial state
// export default reducer
export const login = (user, pass) => async (dispatch) => {
try {
dispatch({ type: LOGIN_REQUEST });
let { data } = await request.post('/login', { user, pass });
await dispatch(loadUserData(data.uid));
dispatch({ type: LOGIN_SUCCESS, data });
} catch(error) {
dispatch({ type: LOGIN_ERROR, error });
}
}
// more actions...
// user.js
import request from 'axios';
// define constants
// define initial state
// export default reducer
export const loadUserData = (uid) => async (dispatch) => {
try {
dispatch({ type: USERDATA_REQUEST });
let { data } = await request.get(`/users/${uid}`);
dispatch({ type: USERDATA_SUCCESS, data });
} catch(error) {
dispatch({ type: USERDATA_ERROR, error });
}
}
// more actions...
::
before your this.onClick
do?
this
), aka this.onClick = this.onClick.bind(this)
. The longer form is usually recommended to do in the constructor, as the short-hand re-binds on every render.
bind()
a lot to pass this
to the function, but I started using () => method()
now.
In redux-saga, the equivalent of the above example would be
export function* loginSaga() {
while(true) {
const { user, pass } = yield take(LOGIN_REQUEST)
try {
let { data } = yield call(request.post, '/login', { user, pass });
yield fork(loadUserData, data.uid);
yield put({ type: LOGIN_SUCCESS, data });
} catch(error) {
yield put({ type: LOGIN_ERROR, error });
}
}
}
export function* loadUserData(uid) {
try {
yield put({ type: USERDATA_REQUEST });
let { data } = yield call(request.get, `/users/${uid}`);
yield put({ type: USERDATA_SUCCESS, data });
} catch(error) {
yield put({ type: USERDATA_ERROR, error });
}
}
The first thing to notice is that we're calling the api functions using the form yield call(func, ...args)
. call
doesn't execute the effect, it just creates a plain object like {type: 'CALL', func, args}
. The execution is delegated to the redux-saga middleware which takes care of executing the function and resuming the generator with its result.
The main advantage is that you can test the generator outside of Redux using simple equality checks
const iterator = loginSaga()
assert.deepEqual(iterator.next().value, take(LOGIN_REQUEST))
// resume the generator with some dummy action
const mockAction = {user: '...', pass: '...'}
assert.deepEqual(
iterator.next(mockAction).value,
call(request.post, '/login', mockAction)
)
// simulate an error result
const mockError = 'invalid user/password'
assert.deepEqual(
iterator.throw(mockError).value,
put({ type: LOGIN_ERROR, error: mockError })
)
Note we're mocking the api call result by simply injecting the mocked data into the next
method of the iterator. Mocking data is way simpler than mocking functions.
The second thing to notice is the call to yield take(ACTION)
. Thunks are called by the action creator on each new action (e.g. LOGIN_REQUEST
). i.e. actions are continually pushed to thunks, and thunks have no control on when to stop handling those actions.
In redux-saga, generators pull the next action. i.e. they have control when to listen for some action, and when to not. In the above example the flow instructions are placed inside a while(true)
loop, so it'll listen for each incoming action, which somewhat mimics the thunk pushing behavior.
The pull approach allows implementing complex control flows. Suppose for example we want to add the following requirements
Handle LOGOUT user action
upon the first successful login, the server returns a token which expires in some delay stored in a expires_in field. We'll have to refresh the authorization in the background on each expires_in milliseconds
Take into account that when waiting for the result of api calls (either initial login or refresh) the user may logout in-between.
How would you implement that with thunks; while also providing full test coverage for the entire flow? Here is how it may look with Sagas:
function* authorize(credentials) {
const token = yield call(api.authorize, credentials)
yield put( login.success(token) )
return token
}
function* authAndRefreshTokenOnExpiry(name, password) {
let token = yield call(authorize, {name, password})
while(true) {
yield call(delay, token.expires_in)
token = yield call(authorize, {token})
}
}
function* watchAuth() {
while(true) {
try {
const {name, password} = yield take(LOGIN_REQUEST)
yield race([
take(LOGOUT),
call(authAndRefreshTokenOnExpiry, name, password)
])
// user logged out, next while iteration will wait for the
// next LOGIN_REQUEST action
} catch(error) {
yield put( login.error(error) )
}
}
}
In the above example, we're expressing our concurrency requirement using race
. If take(LOGOUT)
wins the race (i.e. user clicked on a Logout Button). The race will automatically cancel the authAndRefreshTokenOnExpiry
background task. And if the authAndRefreshTokenOnExpiry
was blocked in middle of a call(authorize, {token})
call it'll also be cancelled. Cancellation propagates downward automatically.
You can find a runnable demo of the above flow
I will add my experience using saga in production system in addition to the library author's rather thorough answer.
Pro (using saga):
Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.
redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.
Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.
Con:
Generator syntax.
Lots of concepts to learn.
API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.
API stability
as an update to reflect the current situation.
I'd just like to add some comments from my personal experience (using both sagas and thunk):
Sagas are great to test:
You don't need to mock functions wrapped with effects
Therefore tests are clean, readable and easy to write
When using sagas, action creators mostly return plain object literals. It is also easier to test and assert unlike thunk's promises.
Sagas are more powerful. All what you can do in one thunk's action creator you can also do in one saga, but not vice versa (or at least not easily). For example:
wait for an action/actions to be dispatched (take)
cancel existing routine (cancel, takeLatest, race)
multiple routines can listen to the same action (take, takeEvery, ...)
Sagas also offers other useful functionality, which generalize some common application patterns:
channels to listen on external event sources (e.g. websockets)
fork model (fork, spawn)
throttle
...
Sagas are great and powerful tool. However with the power comes responsibility. When your application grows you can get easily lost by figuring out who is waiting for the action to be dispatched, or what everything happens when some action is being dispatched. On the other hand thunk is simpler and easier to reason about. Choosing one or another depends on many aspects like type and size of the project, what types of side effect your project must handle or dev team preference. In any case just keep your application simple and predictable.
Update in July 2020:
During the last 16 months, maybe the most notable change in the React community is React hooks.
According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:
hook + async thunk (hook makes everything very flexible so you could actually place async thunk in where you want and use it as normal functions, for example, still write thunk in action.ts and then useDispatch() to trigger the thunk: https://stackoverflow.com/a/59991104/5256695), useRequest, GraphQL/Apollo useQuery useMutation react-fetching-library other popular choices of data fetching/API call libraries, tools, design patterns, etc
In comparison, redux-saga
doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga
was on 18 Sep 2019, which was a long time ago).
But still, redux-saga
provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga
is still a good choice.
Original post in March 2019:
Just some personal experience:
For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.
In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.
Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.
Having reviewed a few different large scale React/Redux projects in my experience Sagas provide developers a more structured way of writing code that is much easier to test and harder to get wrong.
Yes it is a little wierd to start with, but most devs get enough of an understanding of it in a day. I always tell people to not worry about what yield
does to start with and that once you write a couple of test it will come to you.
I have seen a couple of projects where thunks have been treated as if they are controllers from the MVC patten and this quickly becomes an unmaintable mess.
My advice is to use Sagas where you need A triggers B type stuff relating to a single event. For anything that could cut across a number of actions, I find it is simpler to write custom middleware and use the meta property of an FSA action to trigger it.
Thunks versus Sagas
Redux-Thunk
and Redux-Saga
differ in a few important ways, both are middleware libraries for Redux (Redux middleware is code that intercepts actions coming into the store via the dispatch() method).
An action can be literally anything, but if you're following best practices, an action is a plain javascript object with a type field, and optional payload, meta, and error fields. e.g.
const loginRequest = {
type: 'LOGIN_REQUEST',
payload: {
name: 'admin',
password: '123',
}, };
Redux-Thunk
In addition to dispatching standard actions, Redux-Thunk
middleware allows you to dispatch special functions, called thunks
.
Thunks (in Redux) generally have the following structure:
export const thunkName =
parameters =>
(dispatch, getState) => {
// Your application logic goes here
};
That is, a thunk
is a function that (optionally) takes some parameters and returns another function. The inner function takes a dispatch function
and a getState
function -- both of which will be supplied by the Redux-Thunk
middleware.
Redux-Saga
Redux-Saga
middleware allows you to express complex application logic as pure functions called sagas. Pure functions are desirable from a testing standpoint because they are predictable and repeatable, which makes them relatively easy to test.
Sagas are implemented through special functions called generator functions. These are a new feature of ES6 JavaScript
. Basically, execution jumps in and out of a generator everywhere you see a yield statement. Think of a yield
statement as causing the generator to pause and return the yielded value. Later on, the caller can resume the generator at the statement following the yield
.
A generator function is one defined like this. Notice the asterisk after the function keyword.
function* mySaga() {
// ...
}
Once the login saga is registered with Redux-Saga
. But then the yield
take on the the first line will pause the saga until an action with type 'LOGIN_REQUEST'
is dispatched to the store. Once that happens, execution will continue.
For more details see this article.
One quick note. Generators are cancellable, async/await — not. So for an example from the question, it does not really make sense of what to pick. But for more complicated flows sometimes there is no better solution than using generators.
So, another idea could be is to use generators with redux-thunk, but for me, it seems like trying to invent a bicycle with square wheels.
And of course, generators are easier to test.
Here's a project that combines the best parts (pros) of both redux-saga
and redux-thunk
: you can handle all side-effects on sagas while getting a promise by dispatching
the corresponding action: https://github.com/diegohaz/redux-saga-thunk
class MyComponent extends React.Component {
componentWillMount() {
// `doSomething` dispatches an action which is handled by some saga
this.props.doSomething().then((detail) => {
console.log('Yaay!', detail)
}).catch((error) => {
console.log('Oops!', error)
})
}
}
then()
inside a React component is against the paradigm. You should handle the changed state in componentDidUpdate
rather than waiting for a promise to be resolved.
componentDidlMount() { this.props.doSomething().then((detail) => { this.setState({isReady: true})} }
I have recently joined a project that makes heavy use of redux-saga
, and so was also interested in finding out more about the benefits of the saga approach.
TBH, I am still looking. Having read this post and many like it, the 'pros' are elusive. The above answers seem to sum it up as:
testability (ignoring actual API calls), lots of helper functions, familiarity for developers who are used to server-side coding.
Many other claims seem optimistic, misleading or simply false! I've seen many unjustified claims that "thunks cannot do X" for example. But thunks are functions. If a function cannot do X, then javascript cannot do X. So sagas cannot do X either.
For me, the CONS are:
confounding of concerns by using generator functions. Generators in JS return custom iterators. That is all. They do not have any special ability to handle async calls or to be cancellable. Any loop can have a break-out condition, any function can handle async requests, and any code can make use of a custom iterator. When people say thing like: generators have control when to listen for some action or generators are cancellable, but async calls are not then it creates confusion by implying that these qualities are inherent in - or even unique to - generator functions.
unclear use-cases: AFAIK the SAGA pattern is for handling concurrent transaction issues across services. Given that browsers are single-threaded, it is hard to see how concurrency presents a problem that Promise methods can't handle. BTW: it is also hard to see why that class of problem should ever be handled in the browser.
code traceability: By using redux middleware to turn dispatch into a kind of event-handling, Sagas dispatch actions that never reach the reducers, and so never get logged by Redux tools. While other libraries also do this, it is often unnecessarily complicated, given that browsers have event-handling built in. The advantage of the indirection is again elusive, when calling the saga directly would be more obvious.
If this post makes me seem frustrated with sagas, it is because I am frustrated with sagas. They seem like a great solution looking for a problem to solve. IMO.
An easier way is to use redux-auto.
from the documantasion
redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.
No need for other Redux async middleware. e.g. thunk, promise-middleware, saga Easily allows you to pass a promise into redux and have it managed for you Allows you to co-locate external service calls with where they will be transformed Naming the file "init.js" will call it once at app start. This is good for loading data from the server at start
The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.
It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.
Success story sharing
delay
function coming from? Ah, found it: github.com/yelouafi/redux-saga/blob/…redux-thunk
code is quite readable and self-explained. Butredux-sagas
one is really unreadable, mainly because of those verb-like functions:call
,fork
,take
,put
...