0

I know we can use firebase.apps.length to check whether the Firebase is initiated or not.

Eg:

import firebase from 'firebase';

if (!firebase.apps.length) {
   firebase.initializeApp({});
}

export default firebase;

https://github.com/zeit/next.js/issues/1999

However, I read another question on StackOverflow that if we import the same file multiple times, it just runs once (Does ES6 module importing execute the code inside the imported file?)

So the question is why Firebase behaves like that? I mean if this post is true: Does ES6 module importing execute the code inside the imported file?, then we don't need to check firebase.apps.length in the first place because it just runs once no matter how many times we import it

end_lesslove2012
  • 107
  • 4
  • 13

1 Answers1

1

You don't have to use that code to check if Firebase is initialized. Most of the time people just initialize once in a known location, and assume from that point on that it is going to be available later.

If you're in a situation where some code might run repeatedly (like a function call), then you might want to do that check if you want to initialize Firebase lazily.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441