The fork effect in redux-saga is a non-blocking effect used to create a new saga branch that can run concurrently with the parent saga. Common scenarios for using fork include the following:
-
Concurrent Task Execution: When you want to start a new task without blocking the current flow, you can use
fork. This allows multiple tasks to execute simultaneously.Example: In a user login process, if you need to fetch data from multiple sources in parallel, such as user information, user settings, and user messages, you can use
forkto start three differentsagainstances, which will run concurrently without waiting for each other.javascriptfunction* loginFlow() { // ... login logic yield fork(fetchUserInfo); yield fork(fetchUserSettings); yield fork(fetchUserMessages); // ... other logic } -
Non-critical Tasks: If some tasks are secondary or their completion does not affect the continuation of the main flow, you can use
forkto execute them.Example: After submitting form data, you might want to record some statistics, but you don't want the failure of the statistics code to affect the main flow.
javascriptfunction* submitFormSaga(data) { try { yield call(api.submitForm, data); // main task yield put({ type: 'FORM_SUBMIT_SUCCESS' }); yield fork(recordFormSubmitStats, data); // non-critical task } catch (e) { yield put({ type: 'FORM_SUBMIT_FAILURE', message: e.message }); } } -
Long-running Listeners:
forkcan be used to start a task that runs long-term and listens for future actions. It acts as a background task, continuously listening for certain actions without blocking othersaga.Example: A chat application might need a
sagato listen forRECEIVE_MESSAGEactions.javascriptfunction* watchNewMessages() { while (true) { const action = yield take('RECEIVE_MESSAGE'); // handle received message } } function* mainSaga() { // ... yield fork(watchNewMessages); // ... }
When using fork, it's important to note that tasks created by fork do not block the continuation of the parent saga. If you need to ensure that a task completes before proceeding, you should use the call effect. Additionally, errors from fork-created tasks do not propagate to the parent saga, meaning they may silently fail in the background if not handled. Therefore, when starting fork tasks, it's typically necessary to handle errors appropriately within the task.