Reputation: 923
Let's say I have a Node.js library that I need to instantiate in my React app.
const awesomeLibrary = new AwesomeLibrary('someID', options);
awesomeLibrary
allows me to do things like awesomeLibrary.configure()
, awesomeLibrary.specifyCustomProperty()
and awesomeLibrary.fireEvent()
.
I would like to instantiate it once and then call those methods from the instantiated reference (awesomeLibrary
) around my application. What is the best way to that?
Would I instantiate it in top-level entry component (e.g. _app.tsx
), export it, import it into other components and call the methods? In order to export it, I'd have to instantiate it outside the component, instead of in the lifecycle of the component. Is that a bad practice?
Alternatively, could I relegate the instantiation to a hook? Say useAwesomeLibrary()
in which I instantiate and export the methods? But wouldn't doing that create an instance every time the hook is called from different components?
I'm really not sure how to handle this.
Upvotes: 1
Views: 102
Reputation: 944
Instantiating class before exporting it is a fairly common practice and one of the possible implementations of singleton in JavaScript/React. For example, you can use popular i18next
library in this way:
services/i18n.js:
import i18n from 'i18next';
i18n.init({
// pass translations and other config
});
export default i18n;
_app.js:
import i18n from 'services/i18n';
// snip
<I18NextProvider i18n={i18n} /> // consume already instantiated i18n object
The difference between this and instantiating object in a hook is WHEN it will be instantiated. When you do this in hook, it will instantiate every time you mount component with this hook. When in separate file (module), then it will be once per page load.
Is that a bad practice? I don't know, it depends on how you'd use it. There is nothing bad in doing this per se, and even it has its advantages (in the example above we delegated responsibility of creating and configuring i18n service from _app.js, which is very good from Single Responsibility Principle perspective). But keep in mind that codebase bloated with singletons will probably become hard to maintain.
Upvotes: 3