Sean Barnard

Firebase Firestore with React Hooks

This post will describe how I created a custom hook to subscribe to a collection in firestore.

According to the Firebase docs here you can subscribe to a single document or a collection of documents in javascript like this:

Code 1

This particular example targets a collection called “cities” and looks for a doc with the id “SF”.

As this is listening for real time updates if you were to use the result of this in your React state, for example, if this document is changed anywhere else, updates will be made to your state almost instantly and the component will re-render due to the nature of React.

This is really useful because you don’t have to refresh a page to make sure you are seeing the latest version of the data. It will automatically update on screen if it needs to.

When I was playing with this in my own app, I found that I was using this code repeatedly in different components for the main 2 collections used by my app. Although the data is the same, different components in my app do different things with it, but due to the design mostly they require both collections not just one…

So I decided to write a React Hook which can easily be re-used by each component. This was really just a first step to a larger refactor as I have now moved the state up to the app level and pass it down to any/all components that need it via context.

Below is the code for my hook:

Code 2

As you can see this hook takes in a collection name as an argument so you can use this anywhere, for any collection.

The second argument of the onSnapshot function allows you to catch listening errors as detailed in the official docs linked above.

The hook returns an array of 3 items: the data returned from the collection, the current loading status (so you can control the component to not show anything until the data is loaded) and the error status (in case there is a problem which you can handle in your component).

To use this anywhere in the app, you just need the following code:

Code 3

Sean Barnard, software developer at Innovyze.