Redux Saga

1.4.2 · active · verified Wed Apr 22

Redux-Saga is a middleware library for Redux, designed to manage application side effects (like asynchronous data fetching, accessing the browser cache, or impure actions) in a more organized and testable manner. It leverages ES6 Generators to make asynchronous flows look like synchronous code, improving readability and maintainability. The current stable version is 1.4.2, with patch releases occurring relatively frequently and minor versions every few months. Its key differentiators include its declarative effect model, powerful concurrency control patterns (e.g., `takeEvery`, `takeLatest`), and robust testing utilities, providing a structured alternative to Redux Thunk for complex side effect management.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Redux store with `redux-saga` middleware. It demonstrates defining a simple counter reducer, creating an asynchronous saga using generator functions and effect creators (`call`, `put`, `takeEvery`), and running the saga with `sagaMiddleware.run()`.

import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { takeEvery, put, call } from 'redux-saga/effects';

// Reducer
const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

// Sagas
function* incrementAsync() {
  yield call(delay, 1000); // Simulate an async operation
  yield put({ type: 'INCREMENT' });
}

function* delay(ms) {
  return new Promise(res => setTimeout(res, ms));
}

function* rootSaga() {
  yield takeEvery('INCREMENT_ASYNC', incrementAsync);
}

// Create saga middleware
const sagaMiddleware = createSagaMiddleware();

// Create Redux store
const store = createStore(
  counterReducer,
  applyMiddleware(sagaMiddleware)
);

// Run sagas
sagaMiddleware.run(rootSaga);

// Dispatch actions
store.dispatch({ type: 'INCREMENT_ASYNC' });
store.dispatch({ type: 'INCREMENT' });

// Log state changes
store.subscribe(() => console.log(store.getState()));

view raw JSON →