Home > Blockchain >  Firebase: best practice for accessing the database throughout the app
Firebase: best practice for accessing the database throughout the app

Time:06-30

years ago I read in a blog post that developers should define a single database object in their index.ts and export it to use it everywhere in the app like:

export const db = firebase.firestore(); // in v8
export const db = getFirestore(app); // in v9

I used to import that instance in another file to use it in some functions:

import { db } from 'index'

async function foo() {
    const res = await getDoc(db, doc('bar/:baz');
    // ...
}

according to the Firebase Documentation it is not clearly defined whats the best way to get the firestore reference.

Questions:

  1. Is it still the best way to reference the firestore or should it be handled in each file separately?
  2. Does the way of referencing the database object affect my performance in any way?

Disclaimer: If I just missed the explanation in the docs somehow I will delete that post.

Thanks in advance.

CodePudding user response:

it is not clearly defined whats the best way to get the firestore reference.

That's because there is no "best way" to get the reference. The Firebase SDKs deduplicate a lot of calls behind the scenes, which ensures that the most convenient way works in most cases. But the best way depends more in the frameworks that you're using than on the Firebase SDKs themselves, which is why the documentation is intentionally not specifying one best way get a reference.

To your second question:

Does the way of referencing the database object affect my performance in any way?

Not significantly. As said above, the SDKs optimize a lot of the lookups internally, and any gains from reducing the number of calls quickly become meaningless when the SDK needs to make its first network call for your app anyway.

  • Related