Skip to main content
React Native Introduction
CHAPTER 22 Beginner

Firebase Integration

Updated: May 16, 2026
7 min read

# CHAPTER 22

Firebase Integration

1. Introduction

Historically, if a solo developer wanted to build a social media app, they had to write the frontend mobile app, learn a backend language (like Node.js) to write the server API, configure an SQL database, and rent Linux servers to host it all. This took months. Google solved this with Firebase—a Backend-as-a-Service (BaaS). Firebase provides pre-built authentication, real-time databases, and cloud storage, allowing a single developer to build a global, multi-user app in days. In this chapter, we will master Firebase Integration. We will initialize the Firebase SDK, authenticate users via email/password, and perform CRUD operations against a live Cloud Firestore database.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create a new project in the Firebase Web Console.
  • Initialize the Firebase JS SDK within a React Native (Expo) app.
  • Implement Firebase Authentication (Sign Up, Log In, Log Out).
  • Understand the NoSQL architecture of Cloud Firestore.
  • Execute real-time CRUD operations against Firestore collections.

3. Step 1: Firebase Console Setup

  1. 1. Go to console.firebase.google.com and click Create a Project.
  1. 2. Name it (e.g., MyReactNativeApp), disable Google Analytics for now, and click Create.
  1. 3. In the Firebase Dashboard, click the Web icon (</>) to register your app.
  1. 4. Firebase will output a firebaseConfig object containing your API keys. Copy this object!

4. Step 2: SDK Installation and Initialization

In your terminal, install the official Firebase JavaScript SDK:
bash
1
npm install firebase

Create a new file in your project called firebaseConfig.js. We will initialize the connection here!

javascript
1234567891011121314151617181920
import { initializeApp } from &#039;firebase/app&#039;;
import { getAuth } from &#039;firebase/auth&#039;;
import { getFirestore } from &#039;firebase/firestore&#039;;

// Paste the object Google gave you in Step 3 here:
const firebaseConfig = {
  apiKey: "AIzaSyDOCX...",
  authDomain: "my-app.firebaseapp.com",
  projectId: "my-app",
  storageBucket: "my-app.appspot.com",
  messagingSenderId: "123456789",
  appId: "1:123456789:web:abcde"
};

// Initialize the Firebase App
const app = initializeApp(firebaseConfig);

// Export the specific services we want to use in our screens!
export const auth = getAuth(app);
export const db = getFirestore(app);

5. Step 3: Firebase Authentication

In the Firebase Web Console, click Authentication -> Sign-in method and enable Email/Password. Now, we can use the auth object we exported to securely register and log in users!
javascript
123456789101112131415161718192021222324252627
import { auth } from &#039;../firebaseConfig&#039;;
import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from &#039;firebase/auth&#039;;

// 1. REGISTER A NEW USER
const handleSignUp = async (email, password) => {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    console.log("Registered:", userCredential.user.email);
  } catch (error) {
    console.error("Signup Error:", error.message);
  }
};

// 2. LOG IN AN EXISTING USER
const handleLogin = async (email, password) => {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    console.log("Logged In:", userCredential.user.email);
  } catch (error) {
    console.error("Login Error:", error.message);
  }
};

// 3. LOG OUT
const handleLogout = async () => {
  await signOut(auth);
};

*Note: Firebase handles the session automatically! You can replace the AsyncStorage logic from Chapter 21 with a simple onAuthStateChanged listener provided by Firebase.*

6. Step 4: Cloud Firestore (NoSQL Database)

Firebase Auth stores emails, but it cannot store user profiles, chat messages, or shopping carts. We need Cloud Firestore. Firestore is a NoSQL database organized into Collections (Folders) and Documents (Files containing JSON data).

WRITE DATA (Create a User Profile)

javascript
1234567891011121314151617181920
import { db } from &#039;../firebaseConfig&#039;;
import { collection, addDoc, doc, setDoc } from &#039;firebase/firestore&#039;;

// Use addDoc to generate a random ID
const addPost = async () => {
  await addDoc(collection(db, "posts"), {
    title: "My first post!",
    content: "Firebase is amazing.",
    likes: 0
  });
};

// Use setDoc to use a specific ID (like the Auth User ID!)
const saveUserProfile = async (userId, name, age) => {
  await setDoc(doc(db, "users", userId), {
    fullName: name,
    age: age,
    isPro: true
  });
};

READ DATA (Fetch the feed)

javascript
12345678910111213
import { collection, getDocs } from &#039;firebase/firestore&#039;;

const fetchPosts = async () => {
  const querySnapshot = await getDocs(collection(db, "posts"));
  const postsArray = [];
  
  querySnapshot.forEach((doc) => {
    // doc.id is the unique document string, doc.data() is the JSON payload!
    postsArray.push({ id: doc.id, ...doc.data() }); 
  });
  
  console.log(postsArray);
};

7. Real-Time Data Sync

Firestore's greatest superpower is real-time syncing. Instead of getDocs, use onSnapshot. If a user adds a document from a different phone, your screen will update instantly without pulling to refresh!
javascript
1234567
import { onSnapshot, collection } from &#039;firebase/firestore&#039;;

// Call this in a useEffect!
const unsubscribe = onSnapshot(collection(db, "posts"), (snapshot) => {
  const updatedPosts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  setPosts(updatedPosts); // State updates, UI redraws instantly across all devices!
});

8. Visual Learning: The Firestore Tree

txt
123456789
[ /users ] (Collection)
     |
     |-- [ 9xH72... ] (Document auto-ID)
     |       |-- fullName: "Alice"
     |       |-- age: 25
     |
     |-- [ z3P81... ] (Document matched to Auth UID)
             |-- fullName: "Bob"
             |-- age: 30

9. Common Mistakes

  • Typos in Collection Names: If you write collection(db, "user") instead of "users", Firestore will not throw an error. Because it is NoSQL, it assumes you wanted to create a brand new, empty collection named 'user' and will silently write data there. Always double-check your spelling!

10. Best Practices

  • Security Rules: In the Firebase Console, you must write Firestore Security Rules. By default, they might be fully open, meaning any hacker can delete your entire database. You must write rules stating: allow read, write: if request.auth != null; (Only logged-in users can touch the database).

11. Practice Exercises

  1. 1. What Firebase authentication function handles the automatic, secure creation of a new user account, password hashing, and instantaneous login?
  1. 2. Write the nested function path required to point to a specific document with ID 123 inside a collection named products.

12. MCQs with Answers

Question 1

In the Cloud Firestore NoSQL architecture, what is the strict hierarchical rule regarding data storage?

Question 2

When retrieving data from a Firestore getDocs query, why must the developer execute .data() on the returned document object?

13. Interview Questions

  • Q: Explain the paradigm shift in backend development introduced by Backend-as-a-Service (BaaS) platforms like Firebase. Why is it exceptionally popular for startup MVPs?
  • Q: Contrast the execution of a standard getDocs() query with an onSnapshot() listener in Firestore. Provide a distinct UI use-case where onSnapshot is an absolute requirement.
  • Q: Describe the security necessity of Firebase Firestore Rules. How does the mobile client authenticate its requests to the NoSQL database to satisfy these rules?

14. FAQs

Q: Do I need to use the React Native Firebase (@react-native-firebase) library, or the Web SDK (firebase)? A: If you are using the Managed Expo Workflow (which we are), you MUST use the standard web JavaScript SDK (npm install firebase). The @react-native-firebase library requires custom native code and is heavily utilized in Bare React Native CLI projects. Both work perfectly, but the setup is different!

15. Summary

In Chapter 22, we bypassed months of backend server development by integrating Firebase. We established a secure pipeline using the Web SDK, securely authenticating users via Firebase Auth. We navigated the NoSQL architecture of Cloud Firestore, structuring data into scalable Collections and Documents. We executed asynchronous CRUD operations (addDoc, setDoc, getDocs) and tapped into the astonishing power of real-time multi-device synchronization using the onSnapshot listener.

16. Next Chapter Recommendation

Our app can now chat with other users globally in real-time. But what if the user's phone is asleep in their pocket when a message arrives? Proceed to Chapter 23: Push Notifications in React Native.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·