Redux Saga is a middleware library for Redux that helps handle asynchronous tasks in React applications. It is based on the Generator model of JavaScript to handle tasks related to side effects such as calling APIs, handling asynchronous operations, and managing application state.
Redux Saga operates based on the watcher and worker mechanism. The watcher monitors actions and activates the corresponding worker to handle the corresponding asynchronous task. The result of the worker is returned through Redux Saga to update the state in Redux.
To understand Redux Saga better, we need to clarify the following terms:
Here is a simple example of how to use Redux Saga in a React application:
Setting up Redux Saga:
npm install redux-saga
Create a file sagas.js to define watchers and workers:
// sagas.js
import { takeEvery, put, delay } from 'redux-saga/effects';
function* incrementAsync() {
yield delay(1000);
yield put({ type: 'INCREMENT' });
}
function* watchIncrement() {
yield takeEvery('INCREMENT_ASYNC', incrementAsync);
}
export default function* rootSaga() {
yield all([watchIncrement()]);
}
Create a file store.js to connect Redux Saga with Redux:
// store.js
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
export default store;
Using Redux Saga in a React application:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
const incrementAsync = () => {
dispatch({ type: 'INCREMENT_ASYNC' });
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={incrementAsync}>Increment Async</button>
</div>
);
}
export default App;
In the above example, we have created a watcher watchIncrement and a worker incrementAsync. When the user clicks the "Increment Async" button, the INCREMENT_ASYNC action will be sent to Redux Saga to activate the incrementAsync worker. This worker will pause for 1 second (delay(1000)) and then send the INCREMENT action to update the state in Redux.