Skip to content

Instantly share code, notes, and snippets.

@kohlmannj
Last active July 3, 2017 19:10
Show Gist options
  • Save kohlmannj/12cb58f18bfdd2ead883e74cd68a6631 to your computer and use it in GitHub Desktop.
Save kohlmannj/12cb58f18bfdd2ead883e74cd68a6631 to your computer and use it in GitHub Desktop.
A React class component that loads a runtime library on componentDidMount(), but only once for multiple instances.
import React, { Component } from 'react';
// A "global" promise for the runtime library.
const runtimePromise;
export default RuntimeSingletonComponent extends Component {
componentDidMount() {
// Have we previously loaded the runtime library?
if (!runtimePromise) {
// import() the runtime library for the first time.
runtimePromise = import('runtime-lib').then(runtime => runtime);
}
// Use runtimePromise.then() to do something with the runtime library once it's loaded.
// Below: this is an imaginary runtime library which works with DOM elements, so we've
// passed it a reference to the root-level <div> from our render() method.
runtimePromise.then(runtime => {
runtime.init(this.root);
});
}
componentWillUnmount() {
// Use runtimePromise.then() once again to work with the runtime library.
runtimePromise.then(runtime => {
runtime.destroy(this.root);
});
}
render() {
return <div ref={e => { this.root = e; }} />;
}
}
@kohlmannj
Copy link
Author

kohlmannj commented Jul 1, 2017

Question about line 11: I think that could be simplified to:

runtimePromise = import('runtime-lib');

Yes or no? (Namely, is the identity function redundant?)

@kohlmannj
Copy link
Author

Another question: for a runtime library that is used across multiple class components, would it be appropriate to use window.nameOfRuntimeLibraryPromise? Is there a better approach in general?

@kohlmannj
Copy link
Author

kohlmannj commented Jul 1, 2017

Also, I'd have to try it of course, but would it be appropriate or better, for that matter, to use a static class property (e.g. RuntimeSingletonComponent.runtimePromise) instead of the module-local const runtimePromise?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment