Redux Saga: Difference between take and takeEvery

Redux Saga: Difference between take and takeEvery

ยท

2 min read

In Redux Saga, take and takeEvery are two different effect creators used to handle asynchronous actions.

  1. take(actionType): The take 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' });
}
  1. takeEvery(actionType, worker): The takeEvery 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, while takeEvery does not suspend the generator.

  • take allows you to handle a single occurrence of an action, while takeEvery forks a new worker saga for every occurrence of the action.

  • With take, you have more control over when to resume the generator, while takeEvery automatically handles each occurrence of the action.

    Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย