Actually I am a Android Native Developer. I am new to React-Native. In Java i keep the users data and others data in Singleton Class and access from other activities. Then how i achieve this process in React native for access data's from other components or any alternative of singleton in React native.
I just try this but i received the error like getInstance() not defined.
class AppDelegate {
log = "This is AppDelegate";
static myInstance = null;
static getInstance() {
if (AppDelegate.myInstance == null) {
AppDelegate.myInstance = new AppDelegate();
}
return this.myInstance;
}
}
Thank you.
React is UI library, this isn't its responsibility. The question affects any JavaScript application, not only React.
JavaScript modules and ES modules in particular are evaluated only once under normal circumstances, this makes exports singletons:
// exported for extensibility
export class AppDelegate {...}
// a singleton
export default new AppDelegate;
Singleton class is potentially an antipattern in JavaScript. If there's a need for one object, it could be written as object literal.
Imports are cached, so if you export a class, the class will be cached, if you export an instance, the instance will be cached
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With