Skip to content

Instantly share code, notes, and snippets.

@dmueller39
Created July 27, 2017 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmueller39/04b01335c87ab28665812c6807d7462a to your computer and use it in GitHub Desktop.
Save dmueller39/04b01335c87ab28665812c6807d7462a to your computer and use it in GitHub Desktop.
Lazy Higher Order Component
// @flow
import React, { PureComponent } from 'react';
export default function createLazyComponent<A>(
getClass: () => Class<React.Component<void, A, void>>
) {
return class extends PureComponent {
componentWillMount() {
this.lazyComponentClass = getClass();
}
lazyComponentClass: ?Class<React.Component<void, A, void>>;
render() {
const LazyComponent = this.lazyComponentClass;
if (LazyComponent == null) {
return null;
}
return (
<LazyComponent {...this.props}>
{this.props.children}
</LazyComponent>
);
}
};
}
import createLazyComponent from './LazyComponent';
const LazyExpensiveComponent = createLazyComponent(() => require('./ExpensiveComponent'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment