Redux-Saga is a library for managing application state. It installs as middleware to Redux similarly to Redux-Thunk, but the syntax with which it is called is different.

Redux-Saga uses a rather old concept of generators, which appeared together with promises at the JS conference in 2013, but until now was not and still is not a popular solution. It seems quite difficult to understand at first, but it solves a lot of problems in the form of at least the so-called Callback Hell, i.e. nested multiple queries returning results.

Praca na laptopie, Redux-Saga

Keywords in Redux-Saga

Redux-Saga uses keywords in its syntax, such as:

call, put, takeEvery, takeLatest, all 

 

Each of these keywords is used in a function that is a generator, returning objects called Effects.

 

The simplest example would be an API query. In this query, we will retrieve a list of products for our e-commerce store, so that the component that uses the variable with the list of products will automatically reload.

// saga.js
import { call, takeLatest, all } from 'redux-saga/effects'

function* fetchProducts() {
  const products = yield call(Api.fetch, '/products')
}

function* actionWatcher() {
     yield takeLatest('GET_PRODUCTS', fetchProducts)
}

export default function* rootSaga() {
   yield all([
   actionWatcher(),
   ]);
}

// app.js
const sagaMiddleware = createSagaMiddleware();

const store = createStore(
   reducer,
   applyMiddleware(sagaMiddleware),
);
sagaMiddleware.run(rootSaga);

 

The operation of Redux Saga consists of the following:

1. A Redux store is created and we connect our sagaMiddleware to it.
2. The RootSaga using the keyword all accepts a list of other saga objects to which it listens.
3. ActionWatcher using takeLatest listens for changes in the Redux action named GET_PRODUCTS 
4. The component using Redux calls the redux action
5. saga generator fetchProducts is called .

 

Using takeLatest is interesting in the sense - when the same action is called again the previous one is canceled. There are many other elements built into Saga that help manage asynchronicity such as debounce, throttle, delay.

 

Are you looking for a contractor working with Redux-Saga ?
logo

When to use Redux-Saga

Saga seems to be a good replacement for Redux-Thunks, and it's worth trying it yourself in your own project. It comes in handy especially when you are dealing with a complicated interface and many actions. Keywords, or so-called saga effects, solve many problems related to asynchronicity. They can delay queries, determine their maximum frequency, cancel a query as well as many others.

Our offer

Web development

Find out more

Mobile development

Find out more

E-commerce

Find out more

UX/UI Design

Find out more

Outsourcing

Find out more

Related articles

Show all articles