React native- Best way to create singleton pattern
You can use something like that
class SingletonClass {
static instance = null;
static createInstance() {
var object = new SingletonClass();
return object;
}
static getInstance () {
if (!SingletonClass.instance) {
SingletonClass.instance = SingletonClass.createInstance();
}
return SingletonClass.instance;
}
}
var instance1 = SingletonClass.getInstance();
var instance2 = SingletonClass.getInstance();
Here's my implementation for singleton class...
Controller.js
export default class Controller {
static instance = Controller.instance || new Controller()
helloWorld() {
console.log("Hello World... \(^_^)/ !!")
}
}
Usage:
import Controller from 'Controller.js'
Controller.instance.helloWorld()