title: Singleton Object for Dynamically Imported Module in Next.js
body: <p>I'm trying to have a Singleton instance of a dynamically imported module in my Next.js app. However, the current implementation I have seems to initialize a new instance every time I call <code>getInstance</code>.</p>
  <p>Here's the implementation in <code>gui.js</code>:</p>
  <pre><code>let dynamicallyImportPackage = async () =&gt; {
      let GUI;
  
      await import('three/examples/jsm/libs/dat.gui.module.js')
  
      .then(module =&gt; {
          GUI = module.GUI
      })
      .catch(e =&gt; console.log(e))
  
      return GUI;
  }
  
  let GUI = (function () {
      let instance;
  
      return {
          getInstance: async () =&gt; {
              if (!instance) {
                  let GUIModule = await dynamicallyImportPackage();
                  instance = new GUIModule();
              }
  
              return instance;
          }
      };
  })();
  
  export default GUI;
  </code></pre>
  <p>and I call it in an ES6 class function using <code>GUI.getInstance().then(g =&gt; { ... })</code></p>
  <p>I would normally use React Context API or Redux for this kind of shared state but for this case, I need it to be purely in ES6 JS and not React.</p>