redux-saga-skill
AGENTS.md2 starsChanged 3 months agoMITView on GitHub
This document is for AI agents and LLMs to follow when writing, reviewing, or debugging redux-saga code. It compiles all rules and references into a single executable guide. Baseline: redux-saga 1.5.1 with Redux Toolkit (configureStore) Redux-Saga is generator-based middleware for managing complex side effects in Redux applications. Use it for workflow orchestration — parallel tasks, cancellation, racing, channels, and long-running background processes. For data fetching, prefer RTK Query. For simple async, prefer createAsyncThunk. For reactive slice logic, prefer createListenerMiddleware. Every…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 32,671 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- redux-sagaSkill
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 33
Every effect creator must be yielded.
- Very specific: line 51
Never call async functions directly.
- Very specific: line 195
Use expectSaga from redux-saga-test-plan.
- Very specific: line 397
Use action creators from createSlice — no string duplication:
≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Redux-Saga — Complete Guide
This document is for AI agents and LLMs to follow when writing, reviewing, or debugging redux-saga code. It compiles all rules and references into a single executable guide.
Baseline: redux-saga 1.5.1 with Redux Toolkit (configureStore)
Abstract
Redux-Saga is generator-based middleware for managing complex side effects in Redux applications. Use it for workflow orchestration — parallel tasks, cancellation, racing, channels, and long-running background processes. For data fetching, prefer RTK Query. For simple async, prefer createAsyncThunk. For reactive slice logic, prefer createListenerMiddleware.
Table of Contents
- Effects & Yielding — CRITICAL
- Fork Model & Concurrency — CRITICAL
- Testing — HIGH
- Error Handling — HIGH
- Channels & External I/O — MEDIUM
- Recipes & Patterns — MEDIUM
- RTK Integration — MEDIUM
- Troubleshooting — LOW
1. Effects & Yielding
Impact: CRITICAL
Rule: Always Yield Effects
Every effect creator must be yielded. Missing yield creates a synchronous infinite loop that freezes the app.
// INCORRECT — app freezes
while (true) {
const action = take('REQUEST')
call(fetchData, action.payload)
}
// CORRECT
while (true) {
const action = yield take('REQUEST')
yield call(fetchData, action.payload)
}Rule: Use call() for Async Functions
Never call async functions directly. Use yield call() for testability, cancellation, and middleware control.
// INCORRECT — not testable, not cancellable
const user = yield api.fetchUser(id)
// CORRECT
const user = yield call(api.fetchUser, id)call() returns a plain object describing the call — an instruction the middleware executes, not the call itself. Tests use deepEqual against the same effect creator instead of mocks.
Rule: Choose the Right Watcher
| Scenario | Watcher | Why |
| Search / autocomplete | takeLatest | Cancel stale requests |
| Form submission / payment | takeLeading | Prevent duplicate processing |
| Notifications / logging | takeEvery | Process every event |
| Sequential queue | actionChannel + take | One at a time, in order |
| Rate-limited UI events | throttle | Max once per interval |
| Wait for typing to stop | debounce | After silence period |
Effect Creators Quick Reference
| Effect | Blocking | Purpose |
take(pattern) | Yes | Wait for matching action |
takeMaybe(pattern) | Yes | Like take, receives END |
takeEvery(pattern, saga) | No | Concurrent on every match |
takeLatest(pattern, saga) | No | Cancel previous, run latest |
takeLeading(pattern, saga) | No | Ignore until current completes |
put(action) | No | Dispatch action |
putResolve(action) | Yes | Dispatch, wait for promise |
call(fn, ...args) | Yes | Call, wait for result |
apply(ctx, fn, [args]) | Yes | Call with context |
cps(fn, ...args) | Yes | Node-style callback |
fork(fn, ...args) | No | Attached fork |
spawn(fn, ...args) | No | Detached fork |
join(task) | Yes | Wait for task |
cancel(task) | No | Cancel task |
cancel() | No | Self-cancel |
select(selector) | No | Query store state |
actionChannel(pattern) | No | Buffer actions |
flush(channel) | No | Drain buffered messages |
cancelled() | Yes | Check cancellation in finally |
delay(ms) | Yes | Pause execution |
throttle(ms, pattern, saga) | No | Rate-limit |
debounce(ms, pattern, saga) | No | Wait for silence |
retry(n, delay, fn) | Yes | Retry with backoff |
race(effects) | Yes | First wins |
all([effects]) | If any child blocks | Parallel, wait all |
setContext(props) | No | Update context |
getContext(prop) | Yes | Read context |
Pattern Matching
take, takeEvery, takeLatest, takeLeading, throttle, debounce accept:
'*'— all actions (onlytake/takeMaybemay omit the argument entirely)'ACTION_TYPE'— exact match[type1, type2]— any in arrayfn => boolean— custom predicate
For takeEvery, takeLatest, takeLeading, throttle, and debounce the pattern is a required parameter; use '*' for a catch-all watcher. Taking from a multicastChannel also requires a pattern: take(chan, '*'), not take(chan).
2. Fork Model & Concurrency
Impact: CRITICAL
Rule: Attached vs Detached Forks
fork (attached) | spawn (detached) | |
| Parent waits for child | Yes | No |
| Child error crashes parent | Yes | No |
| Parent cancel cancels child | Yes | No |
| Use when | Child is part of the workflow | Child is independent |
// Attached: analytics failure would crash checkout — BAD
yield fork(processPayment)
yield fork(trackAnalytics) // throws → processPayment cancelled
// Correct: analytics is independent
yield fork(processPayment)
yield spawn(trackAnalytics)Rule: Fork Error Propagation
You cannot catch errors from fork() in a try/catch around the fork. Errors bubble to the call() site that invoked the parent.
// INCORRECT — catch never reached
try {
yield fork(failingSaga)
} catch (e) { /* never reached */ }
// CORRECT — catch at the call site
function* root() {
try {
yield call(parentSaga) // errors from forks arrive here
} catch (e) { ... }
}Rule: Never Fork Inside Race
fork is non-blocking — it always wins the race immediately. Use call inside race.
// INCORRECT — fork always wins
yield race({ task: fork(work), timeout: delay(5000) })
// CORRECT
yield race({ result: call(work), timeout: delay(5000) })Concurrency Patterns
actionChannel — Sequential Processing:
const chan = yield actionChannel('REQUEST')
while (true) {
const action = yield take(chan)
yield call(handleRequest, action)
}Worker Pool — Limited Parallelism:
const chan = yield actionChannel('REQUEST')
for (let i = 0; i < 3; i++) yield fork(worker, chan)3. Testing
Impact: HIGH
Rule: Prefer Integration Tests
Use expectSaga from redux-saga-test-plan. It doesn't couple tests to effect ordering.
import { expectSaga } from 'redux-saga-test-plan'
import * as matchers from 'redux-saga-test-plan/matchers'
import { throwError } from 'redux-saga-test-plan/providers'
it('fetches user', () => {
return expectSaga(fetchUserSaga, action)
.provide([[matchers.call.fn(api.fetchUser), user]])
.put(fetchUserSuccess(user))
.run()
})
it('handles error', () => {
return expectSaga(fetchUserSaga, action)
.provide([[matchers.call.fn(api.fetchUser), throwError(new Error('500'))]])
.put(fetchUserFailure('500'))
.run()
})Rule: Use Providers for Mocking
Static providers with partial matchers are preferred:
.provide([
[matchers.call.fn(api.fetchUser), mockUser], // match function, any args
[matchers.select.selector(getToken), 'mock-token'], // mock selector
[matchers.call.fn(api.save), throwError(error)], // simulate error
])Rule: Test Sagas with Reducers
it('loads users into state', () => {
return expectSaga(loadUsersSaga)
.withReducer(usersReducer)
.provide([[matchers.call.fn(api.fetchUsers), users]])
.hasFinalState({ users, loading: false, error: null })
.run()
})Unit Testing (When Order Matters)
import { testSaga } from 'redux-saga-test-plan'
testSaga(checkoutSaga, action)
.next()
.put(showLoading()) // must be first
.next()
.call(api.processPayment) // must be second
.next()
.isDone()Testing Without Libraries (runSaga)
async function recordSaga(saga, action, state = {}) {
const dispatched = []
await runSaga(
{ dispatch: (a) => dispatched.push(a), getState: () => state },
saga, action,
).toPromise()
return dispatched
}Vitest / Jest
Both work identically. expectSaga.run() returns a Promise:
- Jest:
return expectSaga(saga).run() - Vitest:
await expectSaga(saga).run()
4. Error Handling
Impact: HIGH
Rule: Cancellation Cleanup with finally
function* syncSaga() {
try {
while (true) {
yield call(fetchData)
yield delay(10000)
}
} finally {
if (yield cancelled()) {
yield put(syncCancelled())
}
}
}Cancellation propagates downward through attached forks. Each cancelled generator jumps to its finally block.
Rule: Root Saga Error Boundaries
// INCORRECT — one crash kills all
yield all([watchAuth(), watchFetch(), watchAnalytics()])
// CORRECT — isolated error boundaries
function* safeSaga(saga) {
yield spawn(function* () {
try {
yield call(saga)
} catch (e) {
console.error(`${saga.name} failed:`, e)
}
})
}
export default function* rootSaga() {
yield safeSaga(watchAuth)
yield safeSaga(watchFetch)
yield safeSaga(watchAnalytics)
}5. Channels & External I/O
Impact: MEDIUM
eventChannel — External Events
function createSocketChannel(socket) {
return eventChannel((emit) => {
// sanitize: never emit null/undefined; prefer `{ data }` over a bare primitive
socket.on('message', (data) => { if (data != null) emit({ data }) })
socket.on('close', () => emit(END))
return () => socket.close()
})
}Two contract points the docs are explicit about. The subscriber must "sanitize your event sources as to not pass null or undefined through the event channel" — structure the data "like your redux actions. { number } over number." And messages on an eventChannel are not buffered by default: "if not provided, messages will not be buffered on this channel", so anything emitted while no taker is registered is lost. Pass a buffer when every message matters. channel() differs — it queues up to 10 by default — and actionChannel buffers without limit.
Buffer Types
| Buffer | On Overflow |
buffers.none() (eventChannel default) | Drops |
buffers.fixed(n) | Throws |
buffers.expanding(n) | Grows |
buffers.dropping(n) | Drops newest |
buffers.sliding(n) | Drops oldest |
runSaga — Outside Redux
runSaga({ channel, dispatch, getState }, mySaga)6. Recipes & Patterns
Impact: MEDIUM
- Login flow:
forkauth +take(['LOGOUT', 'LOGIN_ERROR'])+cancel - Polling:
while(true)+call+delayin a forked task, cancel onSTOP - Optimistic update:
put(optimistic)+race({ undo: take('UNDO'), commit: delay(5000) }), started withspawnso cancellation can't strand the UI between revert and commit - Pagination:
take('LOAD_MORE')in a loop, track page/hasMore - Batching outgoing side effects:
actionChannel+flushon interval - Batching dispatched actions: wrap
stdChannel().putto unwrapredux-batched-actions'BATCHenvelope, thencreateSagaMiddleware({ channel })— without it, watchers never see batched actions - Timeout wrapper:
race({ result: call(saga), timeout: delay(ms) }) - Parallel loading:
yield all([call(a), call(b), call(c)])
See references/recipes.md for full code examples.
7. RTK Integration
Impact: MEDIUM
configureStore Setup
import createSagaMiddleware from 'redux-saga'
import { configureStore } from '@reduxjs/toolkit'
const sagaMiddleware = createSagaMiddleware()
const store = configureStore({
reducer: rootReducer,
middleware: (getDefault) => getDefault().concat(sagaMiddleware),
})
sagaMiddleware.run(rootSaga) // AFTER store creationSagas with RTK Slices
Use action creators from createSlice — no string duplication:
import { fetchUsers } from './usersSlice'
yield takeLatest(fetchUsers.type, fetchUsersSaga)
yield put(fetchUsersSuccess(users))When to Use What
| Need | Tool |
| Data fetching + caching | RTK Query |
| Simple async | createAsyncThunk |
| Reactive slice logic | createListenerMiddleware |
| Workflows, cancellation, channels | Redux-Saga |
8. Troubleshooting
Impact: LOW
| Symptom | Cause | Fix |
| App freezes | Missing yield in loop | Add yield before every effect |
| Missed actions | Saga blocked on call | Use fork to stay responsive |
| Bad stack traces | Async generators | onError with sagaStack, babel-plugin-redux-saga |
| Saga doesn't start | run() before store | Call run() after configureStore |
| Undefined reaches a saga | Event source emitted null/undefined into an eventChannel | Sanitize at the emit site; emit { data }, not a bare primitive |
yield returns any (TS) | TS can't infer generators | Type manually or use typed-redux-saga |
| Effect not executing | Missing yield before effect | yield put(action) not put(action) |
Prerequisites
redux-saga^1.5.1@reduxjs/toolkit(recommended)redux-saga-test-plan(for testing)- Node.js with ES2015 generator support (all modern runtimes)
License
MIT
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

