Search code examples
reactjsfirebasereact-hooksreactfire

ReactFire / Firebase Hook Placement


I would like to know of a good way to organize reactfire hooks (such as useUser or useFirestoreCollectionData) in a medium-sized application:

  1. I could put hooks in a top-level component, and pass this information as props down to subcomponents (or use a Context to store state).
  2. I could put hooks within each component when needed, so I would end up with multiple useUser or useFirestoreCollectionData hooks.

The second approach decouples some of the components, which is nice since our project is under active development.

However, I am not sure if reactfire or firebase client library has built-in deduplication, compared to libraries such as SWR or react-query. I would prefer to minimize unnecessary reads.


Solution

  • I like to use a offline first approach when using the Firebase databases. None of the awailable libraries could fit our needs so I made my own list of providers where all of them are decoupled. The main goal was:

    • to have all data awailable offline no matter if the app is online or not (this also increases response time for users)
    • to persist realtime listeners for RTDB and Firestore when you have for example a list and go to a single item and back you probably don't want to stop the listener when leaving that list component and start it again when comming back. If you stop and start it the firebase SKD will load all data from the database.

    You can find the providers and an example app here.