Javascript is a great programming language, as time goes by there are more and more new tools based on it, like React Js.

We will review the usage of Redux Saga, which is a middleware library used to control side effects in React projects. To understand this article medium knowledge level in React and Redux is required.

The Side Effects received are request mainly made by us to obtain data from different sources. In general they are API's request or external services. Browser cookies interaction, data bases and real time operation.

Normally, In a React project these functionalities are implemented through a life cycle of a component with the code inside of the same file. In small projects is a great solution. When we have a big project we need to have the side effects centralized and Redux Saga Middleware comes in handy.

The redux structure presents: Actions, Actions Creators, Reducers and a Single Store and thanks to Redux we know concepts like: Render, Props, State, Context, Lifecycle, Events.

Reduce Saga aims to make handling side effects so we can introduce a new concept: Sagas, the saga is like a separate thread in your application that's solely for side effects, as the following shows:

Flowchart

Why a middleware?

The sagas run like middleware because it has Watchers and Workers. The watchers intercept the actions and review if a worker to this action and in this case, run the worker function where the steps to resolve the side effect and carry data to store.

Generator functions (*)

Redux Saga is based on Generator Functions, which are functions that can be exited and later re-entered and their context (Variable Binding) will be saved across re-entraces. Its sintax use asterisc to define a function* and the expression yield / yield*, to program steps, pause the function and give a value or delegate to another generator function respectively.

How to start with Redux Saga:

  1. Create a react app
  2. Add redux to app and configure the store
  3. Add redux saga middleware to store
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootReducer from' ../reducers'
import rootSaga from'../sagas'

// Create the Saga Middleware
const sagaMiddleware = createSagaMiddleware()
// Mount it on the store
const store = createStore(
  reducer, 
  applyMiddleware(sagaMiddleware)
)
// Then, run saga
sagaMiddleware.run(rootSaga)

Saga Helpers and Effects Creators

Redux Saga has helpers and effects creators, to see more about it, check out this presentation

Some advantages of use Redux Saga Middleware:

  • Synchronous looking code with an easy to follow step by step process (hides away the asynchronicity)
  • Can allow for fairly complicate flows
  • Isolates side effect code to a single area of the application.
  • A variety of helper functions and solid documentation.

Reference:

https://redux-saga.js.org/