Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 39
→

How to setup Firebase Integration in React Native ?

How to setup Firebase Integration in React Native ?

November 5, 2026

1. Introduction

Firebase is a Backend-as-a-Service (BaaS) platform developed by Google. It provides ready-to-use backend services that help developers build mobile and web applications without managing every backend component themselves.

With Firebase, we can build applications that support:

  • User registration and login.

  • Cloud database storage.

  • Real-time data synchronization.

  • File and image storage.

  • Push notification services.

  • Application analytics.

  • Crash reporting.

In this tutorial, we will connect a React Native application to Firebase and use Cloud Firestore to manage student records.

Our practical project will support:

  1. Adding student records.

  2. Displaying saved students.

  3. Updating student information.

  4. Deleting student records.

  5. Saving data directly to a cloud database.

  6. Loading records from Firebase.

2. What Is Firebase?

Firebase is a cloud-based application development platform.

Instead of building every backend service from scratch, developers can use Firebase services through SDKs.

Some important Firebase services are:

2.1 Firebase Authentication

Used to manage user authentication, including email/password login and supported social sign-in providers.

2.2 Cloud Firestore

A NoSQL cloud database that stores information in collections and documents.

We will use Cloud Firestore in this tutorial.

2.3 Firebase Realtime Database

A cloud-hosted database that synchronizes data between connected clients in real time.

2.4 Firebase Storage

Used to store files such as images, videos and documents.

2.5 Firebase Cloud Messaging

Used to send notifications to supported devices and applications.

3. Firebase Integration Methods in React Native

There are two commonly used approaches.

Method 1: Firebase JavaScript SDK

The Firebase JavaScript SDK provides access to services such as:

  • Firebase Authentication.

  • Cloud Firestore.

  • Realtime Database.

  • Firebase Storage.

It is suitable for Expo projects and can be used with Expo Go for supported services.

Method 2: React Native Firebase

React Native Firebase connects React Native applications to native Firebase SDKs.

It is useful when an application needs native Firebase capabilities, such as certain Analytics and Crashlytics integrations.

However, React Native Firebase requires custom native code and cannot run inside Expo Go.

Which method will we use?

For this beginner tutorial, we will use:

Expo + Firebase JavaScript SDK + Cloud Firestore

This allows us to build and test our project using Expo Go without additional native configuration.

4. Create a Firebase Account

First, open the official Firebase Console:

https://console.firebase.google.com/

Follow these steps:

  1. Sign in with your Google account.

  2. Click Create a project.

  3. Enter your project name.

  4. Continue through the project setup.

  5. Configure Google Analytics if required, or disable it for this beginner project.

  6. Click Create project.

  7. Wait until Firebase finishes creating your project.

Your Firebase project is now ready.

5. Register Your React Native App with Firebase

After creating the Firebase project:

  1. Open your Firebase project overview.

  2. Click the Web icon represented by </>.

  3. Enter an application nickname.

For example:

ParamClassesReactNative
  1. Click Register app.

  2. Firebase will generate a configuration object.

It will look similar to this:

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

Copy your own configuration values.

Important: Never copy example credentials and expect them to connect to your project. Use the configuration generated by your Firebase Console.

6. Create a Cloud Firestore Database

Now we need to create our database.

Follow these steps:

  1. Open Firebase Console.

  2. Select your project.

  3. Open Build from the sidebar.

  4. Select Firestore Database.

  5. Click Create database.

  6. Select a database location.

  7. Choose the appropriate security configuration.

For this learning project, you can use Firebase's temporary test mode if it is available.

Security warning: Test mode can allow unauthenticated access to your database. It is only for temporary learning and must never be used for a production application. We will cover proper authenticated database rules when we build Firebase Authentication in Tutorial 30.

Your Cloud Firestore database is now created.

7. Understand Firestore Collections and Documents

Firestore uses a collection-and-document structure.

For example:

Firestore Database
│
└── students (Collection)
     │
     ├── Document 1
     │    ├── name: "Rahul"
     │    ├── email: "rahul@gmail.com"
     │    └── course: "React Native"
     │
     ├── Document 2
     │    ├── name: "Amit"
     │    ├── email: "amit@gmail.com"
     │    └── course: "PHP"
     │
     └── Document 3
          ├── name: "Neha"
          ├── email: "neha@gmail.com"
          └── course: "Java"

Collection

A collection is a group of related documents.

Example:

students

Document

A document stores the actual information.

Example:

{
  name: "Rahul",
  email: "rahul@gmail.com",
  course: "React Native"
}

Unlike a traditional SQL database, Firestore is a NoSQL database.

8. Create a React Native Project

Open your terminal and run:

npx create-expo-app@latest FirebaseStudentApp --template blank

Move into the project directory:

cd FirebaseStudentApp

Open the project in Visual Studio Code:

code .

9. Install Firebase SDK

Run the following command:

npx expo install firebase

Use the Expo-compatible Firebase SDK version. Current Expo guidance requires Firebase JavaScript SDK version 12 or later.

10. Create Firebase Configuration File

Inside your project, create a new file:

firebaseConfig.js

Your project structure will look like this:

FirebaseStudentApp/
│
├── assets/
│
├── App.js
│
├── firebaseConfig.js
│
├── package.json
│
└── ...

Open firebaseConfig.js and write:

import { initializeApp, getApp, getApps } from 'firebase/app';

import { getFirestore } from 'firebase/firestore';

// Replace these values with your Firebase project configuration.

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase only once.

const app = getApps().length
  ? getApp()
  : initializeApp(firebaseConfig);

// Initialize Firestore.

const db = getFirestore(app);

export { app, db };

Replace all example configuration values with your actual Firebase configuration.

Understanding the Code

initializeApp()

Initializes Firebase using your project configuration.

getApps()

Checks whether a Firebase application has already been initialized.

getApp()

Returns the existing Firebase application instance.

getFirestore()

Connects the application to Cloud Firestore.

Now Firebase is ready to use in our React Native application.

11. Understand Firestore CRUD Operations

CRUD represents four basic database operations.

Operation Meaning Firestore Method
Create Add new data addDoc()
Read Retrieve data getDocs()
Update Modify existing data updateDoc()
Delete Remove data deleteDoc()

We will use these four operations in our practical application.

11.1 Create Student Record

import {
  collection,
  addDoc
} from 'firebase/firestore';

import { db } from './firebaseConfig';

const addStudent = async () => {

  await addDoc(
    collection(db, 'students'),
    {
      name: 'Rahul',
      email: 'rahul@gmail.com',
      course: 'React Native'
    }
  );

};

collection() identifies the students collection.

addDoc() creates a document with an automatically generated document ID.

11.2 Read Student Records

import {
  collection,
  getDocs
} from 'firebase/firestore';

const getStudents = async () => {

  const snapshot = await getDocs(
    collection(db, 'students')
  );

  const students = snapshot.docs.map((item) => ({
    id: item.id,
    ...item.data()
  }));

  console.log(students);

};

getDocs() retrieves the documents from the collection.

11.3 Update Student Record

import {
  doc,
  updateDoc
} from 'firebase/firestore';

const updateStudent = async (id) => {

  await updateDoc(
    doc(db, 'students', id),
    {
      name: 'Rahul Kumar',
      course: 'Advanced React Native'
    }
  );

};

doc() identifies a specific document.

updateDoc() updates the selected document's fields.

11.4 Delete Student Record

import {
  doc,
  deleteDoc
} from 'firebase/firestore';

const deleteStudent = async (id) => {

  await deleteDoc(
    doc(db, 'students', id)
  );

};

deleteDoc() deletes the selected document.

12. Build the Firebase Student Management App

Now we will combine all four CRUD operations into one application.

Our application will include:

  • Student name input.

  • Student email input.

  • Course input.

  • Add Student button.

  • Student list.

  • Edit Student functionality.

  • Delete Student functionality.

  • Cloud Firestore integration.

Complete App.js Code

Open App.js and replace its existing code with the following:

import React, { useState, useEffect } from 'react';

import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  StyleSheet,
  Alert,
  ActivityIndicator,
} from 'react-native';

import {
  collection,
  addDoc,
  getDocs,
  updateDoc,
  deleteDoc,
  doc,
  serverTimestamp,
} from 'firebase/firestore';

import { db } from './firebaseConfig';

export default function App() {

  const [name, setName] = useState('');

  const [email, setEmail] = useState('');

  const [course, setCourse] = useState('');

  const [students, setStudents] = useState([]);

  const [loading, setLoading] = useState(false);

  const [saving, setSaving] = useState(false);

  const [editId, setEditId] = useState(null);

  // Read student records

  const getStudents = async () => {

    try {

      setLoading(true);

      const snapshot = await getDocs(
        collection(db, 'students')
      );

      const studentList = snapshot.docs.map(
        (item) => ({
          id: item.id,
          ...item.data(),
        })
      );

      setStudents(studentList);

    } catch (error) {

      console.log('Read Error:', error);

      Alert.alert(
        'Error',
        'Unable to load student records.'
      );

    } finally {

      setLoading(false);

    }

  };

  // Add or update student

  const saveStudent = async () => {

    if (
      !name.trim() ||
      !email.trim() ||
      !course.trim()
    ) {

      Alert.alert(
        'Validation',
        'Please enter all student details.'
      );

      return;

    }

    const emailPattern =
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (!emailPattern.test(email.trim())) {

      Alert.alert(
        'Invalid Email',
        'Please enter a valid email address.'
      );

      return;

    }

    try {

      setSaving(true);

      const studentData = {
        name: name.trim(),
        email: email.trim(),
        course: course.trim(),
      };

      if (editId) {

        await updateDoc(
          doc(db, 'students', editId),
          studentData
        );

        Alert.alert(
          'Success',
          'Student updated successfully.'
        );

      } else {

        await addDoc(
          collection(db, 'students'),
          {
            ...studentData,
            createdAt: serverTimestamp(),
          }
        );

        Alert.alert(
          'Success',
          'Student added successfully.'
        );

      }

      clearForm();

      await getStudents();

    } catch (error) {

      console.log('Save Error:', error);

      Alert.alert(
        'Error',
        'Unable to save student information.'
      );

    } finally {

      setSaving(false);

    }

  };

  // Load student data into form

  const editStudent = (student) => {

    setName(student.name);

    setEmail(student.email);

    setCourse(student.course);

    setEditId(student.id);

  };

  // Clear form

  const clearForm = () => {

    setName('');

    setEmail('');

    setCourse('');

    setEditId(null);

  };

  // Delete student

  const deleteStudent = (id) => {

    Alert.alert(
      'Delete Student',
      'Are you sure you want to delete this record?',

      [
        {
          text: 'Cancel',
          style: 'cancel',
        },

        {
          text: 'Delete',

          style: 'destructive',

          onPress: async () => {

            try {

              await deleteDoc(
                doc(db, 'students', id)
              );

              Alert.alert(
                'Success',
                'Student deleted successfully.'
              );

              await getStudents();

              if (editId === id) {
                clearForm();
              }

            } catch (error) {

              console.log(
                'Delete Error:',
                error
              );

              Alert.alert(
                'Error',
                'Unable to delete student.'
              );

            }

          },

        },

      ]

    );

  };

  // Load records when screen opens

  useEffect(() => {

    getStudents();

  }, []);

  // Student list item

  const renderStudent = ({ item }) => (

    <View style={styles.studentCard}>

      <Text style={styles.studentName}>
        {item.name}
      </Text>

      <Text style={styles.studentInfo}>
        Email: {item.email}
      </Text>

      <Text style={styles.studentInfo}>
        Course: {item.course}
      </Text>

      <View style={styles.actionRow}>

        <TouchableOpacity
          style={styles.editButton}
          onPress={() => editStudent(item)}
        >

          <Text style={styles.actionText}>
            Edit
          </Text>

        </TouchableOpacity>

        <TouchableOpacity
          style={styles.deleteButton}
          onPress={() => deleteStudent(item.id)}
        >

          <Text style={styles.actionText}>
            Delete
          </Text>

        </TouchableOpacity>

      </View>

    </View>

  );

  return (

    <View style={styles.container}>

      <Text style={styles.title}>
        Firebase Student App
      </Text>

      <Text style={styles.subtitle}>
        Cloud Firestore CRUD Operations
      </Text>

      <View style={styles.form}>

        <TextInput
          style={styles.input}
          placeholder="Enter Student Name"
          value={name}
          onChangeText={setName}
        />

        <TextInput
          style={styles.input}
          placeholder="Enter Email Address"
          value={email}
          onChangeText={setEmail}
          keyboardType="email-address"
          autoCapitalize="none"
        />

        <TextInput
          style={styles.input}
          placeholder="Enter Course Name"
          value={course}
          onChangeText={setCourse}
        />

        <TouchableOpacity
          style={styles.saveButton}
          onPress={saveStudent}
          disabled={saving}
        >

          <Text style={styles.saveButtonText}>
            {saving
              ? 'Please Wait...'
              : editId
              ? 'Update Student'
              : 'Add Student'}
          </Text>

        </TouchableOpacity>

        {editId && (

          <TouchableOpacity
            style={styles.cancelButton}
            onPress={clearForm}
          >

            <Text style={styles.cancelText}>
              Cancel Edit
            </Text>

          </TouchableOpacity>

        )}

      </View>

      <Text style={styles.listTitle}>
        Student Records ({students.length})
      </Text>

      {loading ? (

        <ActivityIndicator
          size="large"
          color="#2563eb"
        />

      ) : (

        <FlatList
          data={students}
          renderItem={renderStudent}
          keyExtractor={(item) => item.id}
          ListEmptyComponent={
            <Text style={styles.emptyText}>
              No student records found.
            </Text>
          }
          contentContainerStyle={
            students.length === 0
              ? styles.emptyContainer
              : undefined
          }
        />

      )}

    </View>

  );

}

const styles = StyleSheet.create({

  container: {
    flex: 1,
    backgroundColor: '#f1f5f9',
    padding: 18,
    paddingTop: 55,
  },

  title: {
    fontSize: 25,
    fontWeight: 'bold',
    color: '#0f172a',
    textAlign: 'center',
  },

  subtitle: {
    fontSize: 13,
    color: '#64748b',
    textAlign: 'center',
    marginTop: 7,
    marginBottom: 20,
  },

  form: {
    backgroundColor: '#ffffff',
    padding: 15,
    borderRadius: 12,
    marginBottom: 20,
    elevation: 3,
  },

  input: {
    backgroundColor: '#f8fafc',
    borderWidth: 1,
    borderColor: '#cbd5e1',
    padding: 13,
    borderRadius: 8,
    marginBottom: 12,
    fontSize: 15,
  },

  saveButton: {
    backgroundColor: '#2563eb',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
  },

  saveButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },

  cancelButton: {
    padding: 12,
    alignItems: 'center',
  },

  cancelText: {
    color: '#475569',
    fontWeight: 'bold',
  },

  listTitle: {
    fontSize: 19,
    fontWeight: 'bold',
    color: '#0f172a',
    marginBottom: 12,
  },

  studentCard: {
    backgroundColor: '#ffffff',
    padding: 15,
    borderRadius: 10,
    marginBottom: 12,
    elevation: 2,
  },

  studentName: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#1e293b',
    marginBottom: 8,
  },

  studentInfo: {
    fontSize: 14,
    color: '#475569',
    marginBottom: 5,
  },

  actionRow: {
    flexDirection: 'row',
    marginTop: 12,
    gap: 10,
  },

  editButton: {
    flex: 1,
    backgroundColor: '#16a34a',
    padding: 10,
    borderRadius: 7,
    alignItems: 'center',
  },

  deleteButton: {
    flex: 1,
    backgroundColor: '#dc2626',
    padding: 10,
    borderRadius: 7,
    alignItems: 'center',
  },

  actionText: {
    color: '#ffffff',
    fontWeight: 'bold',
  },

  emptyText: {
    color: '#64748b',
    textAlign: 'center',
    marginTop: 20,
  },

  emptyContainer: {
    flexGrow: 1,
  },

});

13. Understand the Complete CRUD Workflow

Step 1: Add Student

The user enters:

Name: Rahul
Email: rahul@gmail.com
Course: React Native

When the user presses Add Student, the saveStudent() function validates the information and calls addDoc().

Firestore creates a new document inside the students collection.

Step 2: Display Students

When the screen opens, useEffect() calls getStudents().

The application retrieves the documents using getDocs() and stores the records in React state.

FlatList displays the student records.

Step 3: Edit Student

When the user presses Edit:

editStudent(item);

The selected student's information is loaded into the input fields.

The user can modify the details and press Update Student.

The application uses updateDoc() to update the selected document.

Step 4: Delete Student

When the user presses Delete, a confirmation dialog appears.

If the user confirms, the application calls:

await deleteDoc(
  doc(db, 'students', id)
);

The selected document is deleted from Firestore.

Step 5: Refresh the Student List

After successful create, update or delete operations, getStudents() retrieves the latest records.

This keeps the application interface synchronized with the database after each operation.

14. Run the Application

Start the Expo development server:

npx expo start

You can test the application using Expo Go on a compatible device or an Android Emulator.

Make sure your device or emulator has internet access.

15. Test Firebase Integration

Follow this testing sequence.

Test 1: Add a Student

Enter:

Name: Rahul
Email: rahul@gmail.com
Course: React Native

Press Add Student.

Expected result:

  • A success message appears.

  • The student appears in the application list.

  • A new document appears in Firestore.

Test 2: Add Another Student

Enter:

Name: Amit
Email: amit@gmail.com
Course: PHP

Press Add Student.

Expected result:

Two student records should appear.

Test 3: Update a Student

  1. Press Edit on Rahul's record.

  2. Change the course to Advanced React Native.

  3. Press Update Student.

Expected result:

The updated course should appear in the application and Firebase Console.

Test 4: Delete a Student

  1. Press Delete on Amit's record.

  2. Confirm deletion.

Expected result:

Amit's record should disappear from the application and Firestore.

16. Verify Data in Firebase Console

Open:

https://console.firebase.google.com/

Follow these steps:

  1. Open your Firebase project.

  2. Select Firestore Database.

  3. Open the Data tab.

  4. Find the students collection.

  5. Open the documents.

You should see the student information stored in the cloud database.

The Firebase Console allows developers to inspect and manage database records.

17. Common Firebase Errors and Solutions

Error 1: Firebase Configuration Error

Reason: Incorrect Firebase configuration values.

Solution:

  • Verify apiKey.

  • Verify projectId.

  • Verify appId.

  • Verify other configuration fields.

  • Ensure the correct Firebase project is selected.

Error 2: Permission Denied

Example:

FirebaseError: Missing or insufficient permissions.

Reason: Firestore security rules do not allow the requested operation.

Solution:

Check your Firestore Rules and confirm that the current user's access is authorized.

For this tutorial, temporary test-mode rules may be used during initial learning, but they must be replaced with secure, authenticated rules before deployment.

Error 3: Network Request Failed

Possible reasons:

  • No internet connection.

  • Incorrect Firebase configuration.

  • Network restrictions.

  • Firebase service connectivity problems.

Solution:

Check the internet connection and verify the Firebase project configuration.

Error 4: Student Records Are Not Displayed

Possible reasons:

  • Incorrect collection name.

  • Firestore permission restrictions.

  • Database contains no documents.

  • A request failed.

Solution:

Check the collection name and Firebase Console, then inspect the application logs.

Error 5: Firebase Already Initialized

Reason: Firebase initialization was attempted multiple times.

Solution:

Use getApps() and getApp() to reuse the existing Firebase application instance, as demonstrated in firebaseConfig.js.

18. Firebase Security Best Practices

Firebase configuration values are required by the client SDK. The API key in a Firebase client configuration is not a substitute for database authorization.

Follow these practices:

  1. Configure Firestore Security Rules.

  2. Do not allow unrestricted public database access in production.

  3. Use Firebase Authentication to identify users.

  4. Restrict documents according to the authenticated user's permissions.

  5. Validate important data on trusted server-side systems.

  6. Do not store passwords in Firestore as plain text.

  7. Never put server credentials or private service-account keys inside a mobile application.

  8. Consider Firebase App Check to help protect backend resources against unauthorized clients.

  9. Monitor database usage and billing.

19. Firebase JavaScript SDK vs React Native Firebase

Feature Firebase JS SDK React Native Firebase
Expo Go Supported services work Not supported
Native configuration Usually simpler Required
Firestore Supported Supported
Authentication Supported Supported
Realtime Database Supported Supported
Native Analytics Limited mobile support Supported
Crashlytics Not supported as a native service Supported

Choose the SDK based on the Firebase features and native capabilities your application requires.

20. Practical Exercises

Complete these exercises to improve your Firebase skills.

Exercise 1: Add a phone number field to the student form.

Exercise 2: Add a search feature to find students by name.

Exercise 3: Add a course filter.

Exercise 4: Display the total number of student records.

Exercise 5: Add a refresh button to reload Firestore data.

Exercise 6: Add a created date to each student record.

Exercise 7: Explore Firestore Security Rules and understand how access can be restricted.

21. Frequently Asked Questions

Q1. What is Firebase in React Native?

Firebase provides cloud backend services that can be integrated into React Native applications.

Q2. Can we use Firebase with Expo?

Yes. Firebase JavaScript SDK can be used with Expo, including Expo Go for supported services.

Q3. What is Cloud Firestore?

Cloud Firestore is a cloud-hosted NoSQL database that stores data in collections and documents.

Q4. What is the difference between Firestore and MySQL?

Firestore is a NoSQL document database, whereas MySQL is a relational SQL database that organizes data into tables and rows.

Q5. Can Firebase store images?

Yes. Firebase Storage can be used to store images and other files.

Q6. Can Firebase provide user login?

Yes. Firebase Authentication provides services for user registration, login and identity management.

Q7. Is Firebase free?

Firebase provides a no-cost Spark plan and a pay-as-you-go Blaze plan. Available features, quotas and billing depend on the service and plan.

Q8. Can we use Firebase without creating our own PHP backend?

Yes. Firebase provides client SDKs and cloud services that can handle many common backend requirements. More complex applications may still need trusted server-side logic.

22. Conclusion

In this tutorial, we learned how to integrate Firebase into a React Native application using Expo and the Firebase JavaScript SDK.

We covered:

  • Creating a Firebase project.

  • Registering a React Native application.

  • Creating a Cloud Firestore database.

  • Installing Firebase SDK.

  • Configuring Firebase.

  • Understanding collections and documents.

  • Adding student records.

  • Reading student records.

  • Updating student records.

  • Deleting student records.

  • Testing cloud database operations.

  • Understanding Firebase security.

Finally, we built a complete Firebase Student Management App with CRUD functionality.

Firebase makes it easier to add cloud database capabilities to modern mobile applications without building every backend service from scratch.

←
Post 28 of 39
→