Blog>
Snippets

Dynamic Sagas for Code Splitting

Explain and demonstrate how to implement dynamic sagas for the purpose of code splitting and lazy loading features in a React application, enabling on-demand saga instantiation to optimize initial load time.
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  rootReducer,
  applyMiddleware(sagaMiddleware)
);

sagaMiddleware.run(rootSaga);

export default store;
This code initializes Redux store with saga middleware. It's the base setup before enhancing with dynamic sagas.
function* dynamicSagaWatcher(action) {
  // Load saga dynamically based on action type
  if (action.type === 'LOAD_USER_FEATURE_SAGA') {
    const { default: userFeatureSaga } = yield import('./features/userFeatureSaga');
    yield* userFeatureSaga();
  }
}
Defines a watcher saga to listen for a specific action that triggers loading of a dynamic saga. When the action is dispatched, the code dynamically imports the saga associated with that feature.
import { fork, all } from 'redux-saga/effects';

export default function* rootSaga() {
  yield all([
    fork(dynamicSagaWatcher),
    // You can fork other sagas here
  ]);
}
Modifies the rootSaga to include the dynamicSagaWatcher. It's listening for actions to dynamically load other sagas, allowing code splitting at the saga level.
dispatch({ type: 'LOAD_USER_FEATURE_SAGA' });
Dispatches an action to trigger the dynamic loading of the user feature saga. Use this action in your component when you want to load the corresponding saga dynamically.