Installing Redux Saga
Three steps to add Redux Saga to a React-Redux app: install the package, create the middleware instance, and add it to applyMiddleware. Nothing runs until saga.run() is called.
Redux Saga is middleware. Like every Redux middleware, it needs to be installed, instantiated, and added to the store before it intercepts anything. This post covers exactly those three steps -- no saga logic yet, just the plumbing.
[!TIP] Run this yourself: The setup code is in the code-practice repo. Run
node store.jsto confirm the middleware loads without error.
Install the Package
npm install redux-saga --save--save puts it in dependencies, not devDependencies. Sagas run in production.
Create the Middleware Instance
redux-saga exports a single function: createSagaMiddleware. Call it once before creating the store.
import createSagaMiddleware from 'redux-saga';
const saga = createSagaMiddleware();The returned saga object has two roles: it goes into applyMiddleware(), and it exposes the .run() method used later to start sagas.
Add It to the Store
Pass the instance to applyMiddleware alongside any other middleware. Logger must remain last.
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import allReducers from '../reducers';
const saga = createSagaMiddleware();
const store = createStore(
allReducers,
composeWithDevTools(
applyMiddleware(saga)
)
);
export default store;At this point the middleware is mounted. Saga is watching the action stream, but no sagas are registered yet. Every dispatched action flows through unchanged.
ExpandRedux Saga middleware position in the action pipeline
What Comes Next
The next step is telling Saga what to run. That is saga.run(rootSaga) -- but it must be called after createStore(), and the root saga must exist first. The next post covers both.
The Essentials
createSagaMiddleware()creates the instance. Call it once, with no arguments. The return value goes into bothapplyMiddlewareand.run().- Add it to the store like any other middleware. Its position relative to Thunk is flexible. Logger always stays last.
- The middleware is idle after mounting. No sagas run until
saga.run()is called. Dispatched actions pass through without being intercepted.
Further Reading and Watching
- Boris Dinkevich: Practical Advanced Redux (ReactNext 2017): a conference talk walking through how middleware chains work in a real production Redux app
- Redux Saga Getting Started: the official guide showing the same three-step store setup with an annotated example
Practice what you just read.
Keep reading