In Redux Saga, take
and takeEvery
are two different effect creators used to handle asynchronous actions.
take(actionType)
: Thetake
effect listens for a specific action of a given type and suspends the generator until that action is dispatched. Once the action is dispatched, the generator resumes execution and returns the dispatched action. If the action has already been dispatched before the generator starts listening, the generator will not suspend and continue execution from where it left off.
Example:
import { take, put } from 'redux-saga/effects';
function* mySaga() {
yield take('FETCH_DATA'); // Suspends until 'FETCH_DATA' action is dispatched
yield put({ type: 'DATA_RECEIVED' });
}
takeEvery(actionType, worker)
: ThetakeEvery
effect listens for every occurrence of a specific action of a given type and forks a new worker saga to handle each occurrence. It does not suspend the generator and allows the generator to continue execution without waiting for the dispatched action.
Example:
import { takeEvery, put } from 'redux-saga/effects';
function* workerSaga(action) {
yield put({ type: 'DATA_RECEIVED', payload: action.payload });
}
function* mySaga() {
yield takeEvery('FETCH_DATA', workerSaga); // Listens for every 'FETCH_DATA' action
}
In summary, the key differences between take
and takeEvery
are:
take
suspends the generator until a specific action is dispatched, whiletakeEvery
does not suspend the generator.take
allows you to handle a single occurrence of an action, whiletakeEvery
forks a new worker saga for every occurrence of the action.With
take
, you have more control over when to resume the generator, whiletakeEvery
automatically handles each occurrence of the action.
ย