Last active
July 3, 2017 19:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; }} />; | |
} | |
} |
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?
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
Question about line 11: I think that could be simplified to:
Yes or no? (Namely, is the identity function redundant?)