When should I use yield* vs yield in redux-saga?

Viewed 8568

I want to call another saga from a saga.

The saga is of course a generator function, and is asynchronous.

Should I ever user yield * or should I always use yield?

function* mySaga({ payload: { id, name } }) {
    yield myOtherAsyncSaga(); // when to use yield *?
}
2 Answers

TLDR: always use yield* for performance and correct type resolution in TS

If you are on JS land, yield gives the middleware a Generator and the middleware will automatically iterate it. If you use yield*, you are iterating the generator and yielding all the items to the middleware. There is no big difference in this case, except that hitting the middleware is slower.

When using TypeScript, things change a bit: yield means that the iteration of the generator will happen in the middleware and because of that our types will be incorrect. If instead we use yield*, the iteration will happen on our scope and TS will be able to detect the proper types.

There is a small TS library that illustrates this better: https://www.npmjs.com/package/typed-redux-saga

Related