Blog>
Snippets

Dynamic saga injection for code-splitting

Demonstrate how to dynamically inject sagas as part of code-splitting strategy to optimize performance and maintainability of the application.
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  rootReducer,
  applyMiddleware(sagaMiddleware)
);
Setup Redux store with saga middleware.
function injectSaga(key, saga) {
  if (!store.injectedSagas[key]) {
    store.injectedSagas[key] = saga;
    sagaMiddleware.run(saga);
  }
}
Define a function to inject sagas dynamically by ensuring a saga is only injected once using a unique `key`.
function* rootSaga() {
  yield all([
    // other sagas
  ]);
}
sagaMiddleware.run(rootSaga);
Setup a rootSaga to run initially loaded sagas.
import { useEffect } from 'react';
import { injectSaga } from './sagas';
import myPageSaga from './myPageSaga';

const MyPage = () => {
  useEffect(() => {
    injectSaga('myPage', myPageSaga);
    return () => {/* logic to cancel saga if needed */};
  }, []);

  return (<div>My Page Content</div>);
};
Inject a saga on a page component using useEffect hook to make sure it runs once the component mounts. This could be useful for code-splitting where sagas are loaded only when needed.