React hooks with Firebase v9

None of the current React hooks for the RealTimeDB works with the Firebase v9 SDK release. So, I wrote my own.

React hooks with Firebase v9

React and Firebase has been a reliable way for me to implement projects in school and in my personal life. Personally, I call this stack ReBase (ok, the name is a WIP). But here comes the problem: none of the current React hooks for the RealTimeDB works with the Firebase v9 SDK release. So, I wrote my own.

Note: as of writing, react-firebase-hooks doesn't support V9 and reactfire does not support RealTimeDB.

Note2: All code samples will be in TypeScript and written on https://carbon.now.sh.

What am I implementing?

In this short post, I will demonstrate 2 tiny custom react hook that allowed me to read Firebase in a Reactive way with ReactJS. I will not go into the details of the V9 SDK since they are well covered by Fireship on Youtube.

What am I not implementing?

The write APIs for react v9 are rather straightforward. I did write a simple abstraction for my school project, but they are very simple and not a lot to look at, so I would skip over them.

User Authentication - useUserAuthenticated

In one of my school projects, I wanted to implement restricted routes - routes that are only accessible to an authenticated user.

The authenticated state will be forced into a boolean whenever the user's authentication status changes. It can then be used to control routing and other aspects of the application that requires the user to be authenticated.

And since it is a React state, it will work with any other React APIs (mainly useEffect).

Reactive Data - useReactiveRef

Now that we reactively restrict the user's access to different routes, we need to have our data be reactive too.

The data state will be reactive to the firebase's state, and we can treat it like normal React data, allowing it to trigger useEffect or conditional rendering in our components.

At work I have been working with GraphQL for the past few months. And I have since got used to apollo-client's API and designed my hook around an API interface similar to that, with a reactive data/error response and loading/empty boolean states.

Consumption

The useReactiveRef hook returns an object that holds a few reactive state. Realistically we only care about data, but the others could provide us with context about error handling.

The consumption for useUserAuthenticated is rather straightforward, so I don't think I would need to explain that.


Photo by Oussama Elhaidi from Pexels.