Redux-saga is a library used to improve and simplify side-effects implementation in React Redux applications. Some of them are asynchronous actions like data load or access to the browser cache.
Think of saga as a separate thread in your app that handles side-effects. Redux-saga can be called as a middleware as simple redux actions can start, stop and cancel this thread in the main application. It has access to the full redux state and it can dispatch redux actions.
Where to start
$ npm install –save redux-saga
$ yarn add redux-saga
Let’s consider having an interface for retrieving some user data from a remote server after clicking on a button.
The components are dispatching an action as a simple Store object. We’ll create saga that will listen to all USER_FETCH_REQUESTED actions triggers API calls for retrieving user data.
We start “fetchUser” for every dispatched `USER_FETCH_REQUESTED` action. It helps us receive user data simultaneously.
You can use “takeLatest” as an alternative. It doesn’t allow retrieving data from several users. If “USER_FETCH_REQUESTED” is dispatched while the previous request is awaiting the response, this request will be canceled, the last request will be handled.
We should connect saga to the Redux Store with the help of redux-saga middleware to start it.
We create saga middleware.
We mount it to the Store.
We start saga.
And we render the application.
Using UMD builds in a browser
There’s a umd build available in dist/ directory. redux-saga is available as ReduxSaga in window object while using the umd builds. This build is helpful if you are not using Webpack or Browserify.
If your browser doesn’t support ES2015 generators, you should enable a working polyfill that should be imported to redux-saga:
Building examples from the source files
It’s a demo using webpack and takeEvery high-level API.
Here’s a low-level API for displaying the task cancellation.