Using Firebase With React Context
Serverless architecture for building web and mobile apps has become increasingly popular. By offloading the work required to maintain servers and write backend code, small teams of developers are able to move much faster and scale their apps to millions of people at a low cost. One really popular serverless framework is Google’s Firebase. Today, I will be discussing how to integrate Firebase into a React application with a React context so that it is available to your entire application.
Project Setup
Before running to the races with our shiny new React app, we need register a new app on Firebase. This can be done by hitting “+” on https://console.firebase.google.com/ and following the setup steps. Hint: update the unique identifier with a cool name for your project after entering the name.
Now head on over to the project settings, and select “Config” under “Firebase SDK snippet”. Take a note of these values because we will need them soon.
Next, create a react app and install firebase from npm
yarn create-react-app cool-serverless-appcd cool-serverless-app/yarn add firebase
Firebase Class
We will be wrapping the Firebase library in a class that will give access to only the functions that are needed. This class will also perform initialization with the config variables when it is instantiated. In this example, I will only be using the Realtime Database function, however, the process to use other functionality such as Auth or Cloud Firestore is as simple as adding another line to the class.
The constructor checks to make sure no apps have been defined yet before initializing with the config variables. The environment variables used in firebaseConfig
are defined in a .env
file in the project root. Starting up the app will pick these variables up and put them on the process.env
object. Note: create-react-app only picks up variables with the prefix REACT_APP_
.
Defining the React Context
Instead of passing the Firebase instance down to every component that needs it, we will be using a React Context to provide it to the entire application. In addition, I will also use the useContext
hook which can be used to consume the value provided by the context.
The useFirebase
hook provides an easy way to grab the value of the nearest FirebaseContext
provider. If there is no context provider where the hook is used, this will throw so that issues are caught early.
Application Code
With the context defined, it can now be used within the react application. In App.js:
In this simple example, it’s easy to see the benefit of using the context. Each child component can simply just pull the Firebase instance from the context provider instead of having it get drilled down.
Cheers