Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await
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 eachexpires_in
millisecondsTake 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.
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.