Blog>
Snippets

Dynamically Injecting a Feature Saga for Code Splitting

Demonstrate how to dynamically inject a saga when a specific route is accessed, to achieve code splitting and reduce initial load time.
function* featureSaga() {
  // Your saga logic here, e.g., listening to specific actions
takeLatest('FEATURE_ACTION', featureActionHandler);
}
Defines the feature saga that will be dynamically injected. This saga will listen to `FEATURE_ACTION` and execute `featureActionHandler` in response.
function injectSaga(store, saga) {
  // Dynamically start a new saga
  store.runSaga(saga);
}
Utility function to inject a saga into the redux store dynamically. It utilizes `store.runSaga` method to start the saga.
if (route === 'featureRoute') {
  injectSaga(store, featureSaga);
}
Conditionally injects `featureSaga` when a specific route, `featureRoute`, is accessed. It's assumed this check happens within a route change listener or a similar setup.