Skip to content

Instantly share code, notes, and snippets.

@xeqlol
Last active October 13, 2018 15:19
Show Gist options
  • Select an option

  • Save xeqlol/1032a192fb278b27a304a6f8eff0b6a8 to your computer and use it in GitHub Desktop.

Select an option

Save xeqlol/1032a192fb278b27a304a6f8eff0b6a8 to your computer and use it in GitHub Desktop.
react + redux + saga code splitting mind experiment
import { wrapModule } from './loader';
const About = ... // component, connected to store;
const aboutReducer = ... // root reducer
const aboutSaga = ... // root saga
export default wrapModule(About, aboutReducer, aboutSaga);
import { wrapModule } from './loader';
const Home = ... // component, connected to store;
const homeReducer = ... // root reducer
const homeSaga = ... // root saga
export default wrapModule(Home, homeReducer, homeSaga);
import { store, sagaMiddleware } from 'somewhere where store and sagaMiddleware were initialized'
export function createLoadableComponent(store, sagaMiddleware) {
// that looks awful, needs some research
const loadedModules = {};
const loadedReducers = {};
const loadedComponents = {};
return (componentName, loader) => {
return class LoadableComponent extends React.Component {
state = { componentLoaded: false, component: null };
componentWillMount() {
if (loadedModules[componentName]) {
this.setState({
componentLoaded: true,
component: loadedComponents[componentName]
});
return;
}
loader().then(module => {
console.log(`module ${componentName} loaded`);
const { container, reducer, saga } = module.default;
loadedModules[componentName] = true;
loadedComponents[componentName] = container;
loadedReducers[componentName] = reducer;
store.replaceReducer(combineReducers(loadedReducers));
sagaMiddleware.run(saga);
this.setState({ componentLoaded: true, component: container });
});
}
render() {
if (!this.state.componentLoaded) {
return <div>loading</div>;
}
const Component = this.state.component;
return <Component />;
}
};
};
}
export const loadable = createLoadableDecorator(store, sagaMiddleware);
export function wrapModule(container, reducer, saga) {
return {
container,
reducer,
saga
};
}
import { loadable } from './loader'
export const Home = loadable('Home', () => import('./HomeContainer'));
export const About = loadable('About', () => import('./AboutContainer'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment