Search code examples
reactjsreact-routerreact-router-reduxreact-boilerplate

Code-splitting and async code loading in react-boilerplate


I started using react-boilerplate for my project and I'm trying to figure out how routing works there. Could you please explain me this example in docs or example in app?

  • Why is getComponent() function so large relatively to simple react-router route definition <Route path='somepath' component={SomeContainer} />?
  • Why should we call injectReducers and injectSagas?

Thanks!

path: '/posts/:slug',
name: 'post',
getComponent(nextState, cb) {
 const importModules = Promise.all([
   import('containers/Post/reducer'),
   import('containers/Post/sagas'),
   import('containers/Post'),
 ]);

 const renderRoute = loadModule(cb);

 importModules.then(([reducer, sagas, component]) => {
   injectReducer('post', reducer.default);
   injectSagas(sagas.default);
   renderRoute(component);
 });

 importModules.catch(errorLoading);
},

Solution

  • injectReducer and injectSagas are for code splitting. The code is saying "when this route is called, load these reducers and sagas". Webpack looks at that and splits code into different files accordingly.

    Not really necessary if it's a small app, but if it's something huge, code splitting can be helpful to keep initial load times down.