Skip to content

Instantly share code, notes, and snippets.

@dave-nicholas
Last active March 11, 2018 13:40
Show Gist options
  • Save dave-nicholas/1480219bede6a0523e67da7339998b2b to your computer and use it in GitHub Desktop.
Save dave-nicholas/1480219bede6a0523e67da7339998b2b to your computer and use it in GitHub Desktop.
A composed HOC for code splitting in react (requires recompose)
import React from 'react';
import { withState, compose, lifecycle } from 'recompose';
export default componentToImport => {
const state = withState('component', 'setComponent', null);
const hooks = lifecycle({
async componentDidMount() {
const { default: C } = await componentToImport();
this.props.setComponent(() => props => <C {...props} />);
}
});
const AsyncComponent = ({ component: C, ...props }) =>
C ? <C {...props} /> : null;
const AsyncContainer = compose(state, hooks)(AsyncComponent);
return AsyncContainer;
};
import AsyncContainer from './AsyncContainer';
const AsyncSomething = AsyncContainer(() => import('./somecomponent'));
/* ............ */
<Route component={AsyncSomething} path='/something' />
/* ............ */
<AsyncSomething />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment