Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Java singleton in React Native?

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.

like image 379
Sabish.M Avatar asked Mar 04 '23 02:03

Sabish.M


2 Answers

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.

like image 117
Estus Flask Avatar answered Mar 12 '23 05:03

Estus Flask


Imports are cached, so if you export a class, the class will be cached, if you export an instance, the instance will be cached

like image 20
Mosè Raguzzini Avatar answered Mar 12 '23 06:03

Mosè Raguzzini