Home  >  Q&A  >  body text

When using Firebase in React, should getAuth getStorage getFirestore etc. be called once and passed or can they be called in every component?

If I need the result of using const db = getFirestore() or const auth = getAuth(app) etc. in multiple components, I should:

  1. Whenever I need, rewrite these lines in each component const db = getFirestore() or const auth = getAuth(app) etc, or

  2. Only call them at the top level of the App component and then pass them as props to child components to avoid multiple calls?

I feel option 1 is easier to code, but may result in a performance penalty. What is the correct way to do this in React/Firebase coding?

P粉788571316P粉788571316249 days ago333

reply all(1)I'll reply

  • P粉893457026

    P粉8934570262024-01-17 18:38:52

    getFirestore(...), getAuth(...) and similar calls are simple local calls that initialize some basic objects from the configuration. There's no harm in calling them in multiple places.

    That said, I'd recommend passing app to all of them, or to none, unlike what the code in your question does now.

    So, either get all services from the default application:

    const db = getFirestore();
    const auth = getAuth();

    or Get all content from the specified application:

    const db = getFirestore(app);
    const auth = getAuth(app);

    But not a mix of these.

    reply
    0
  • Cancelreply