Provide Firebase in React

Now, we'll learn how to use Firebase in our React application.

In the previous lessons, we created a Firebase class but we have not used it in our React application yet. In this lesson, we’ll connect Firebase with the React world.

Different Approaches

The simpler approach would be to create a Firebase instance with the Firebase class and then import the instance (or class) in every React component where it’s needed, but that is not a good approach for two reasons:

  • It will be more difficult to test our React components.
  • Firebase should only be initialized once in our application (singleton) and by exposing the Firebase class to every React component, we could end up with multiple Firebase instances by mistake.

The alternative way is to use React’s Context API to provide a Firebase instance once at the top-level of our application’s component hierarchy.

Create a new src/components/Firebase/context.js file in your Firebase module and implement the code given below:

Get hands-on with 1400+ tech skills courses.