ReactHard
What is Redux Saga?
Redux Saga is a middleware library that manages side effects with generator functions called sagas. Sagas listen for actions and yield declarative effects such as call (run an async function), put (dispatch), take (wait for an action) and fork (start a background task), which makes complex async flows, cancellation, debouncing and races easy to express and test.
Key effects
takeEvery(type, worker): run a worker for every matching action.takeLatest(type, worker): cancel the previous run when a new action arrives (ideal for search).call(fn, ...args): call a function (usually returning a promise) and wait.put(action): dispatch an action.select(selector): read state.fork,spawn,cancel: manage background tasks.race,all,delay,debounce,throttle: coordination helpers.
Strengths
- Long-running workflows: polling, websockets, multi-step onboarding, retries with backoff.
- Built-in cancellation semantics.
- Testable: effects are plain objects, so tests can step through a generator without mocking.
Weaknesses
- Generators and the effect vocabulary have a learning curve.
- Extra indirection for simple fetches.
- Much of its use has been replaced by RTK Query (data fetching) and the RTK listener middleware (reacting to actions).
Status
Redux Saga is still maintained (version 1.6) and common in older enterprise codebases. For new projects, the Redux team recommends RTK Query and listeners first.
Code example
tsx
1import { call, put, takeLatest, delay } from "redux-saga/effects";2import createSagaMiddleware from "redux-saga";3import { configureStore, createSlice, type PayloadAction } from "@reduxjs/toolkit";45const search = createSlice({6 name: "search",7 initialState: { results: [] as string[], loading: false },8 reducers: {9 queryChanged: (s, _a: PayloadAction<string>) => void (s.loading = true),10 resultsLoaded: (s, a: PayloadAction<string[]>) => { s.loading = false; s.results = a.payload; },11 },12});1314function* searchWorker(action: PayloadAction<string>): Generator<any, void, any> {15 yield delay(300); // debounce: takeLatest cancels this if a new query arrives16 const res = yield call(fetch, `/api/search?q=${encodeURIComponent(action.payload)}`);17 const data: string[] = yield call([res, "json"]);18 yield put(search.actions.resultsLoaded(data));19}2021function* rootSaga() {22 yield takeLatest(search.actions.queryChanged.type, searchWorker);23}2425const sagaMiddleware = createSagaMiddleware();26export const store = configureStore({27 reducer: { search: search.reducer },28 middleware: (getDefault) => getDefault({ thunk: false }).concat(sagaMiddleware),29});30sagaMiddleware.run(rootSaga);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.