Bird
Raised Fist0
React Nativemobile~20 mins

Why Firebase powers mobile backends in React Native - Build It to Prove It

Choose your learning style10 modes available
Build: Firebase Features Demo
This screen shows why Firebase is a great choice for mobile backends by demonstrating user authentication and real-time data updates.
Target UI
---------------------------------
| Firebase Features Demo         |
|-------------------------------|
| [Sign In Button]               |
|                               |
| Messages:                     |
| - Welcome to Firebase!         |
|                               |
| [Add Message Button]           |
---------------------------------
Add a Sign In button that simulates user login
Display a list of messages stored in Firebase Realtime Database
Add a button to add a new message to the database
Show real-time updates when messages change
Use Firebase Authentication and Realtime Database
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, onValue, push } from 'firebase/database';
import { getAuth, signInAnonymously } from 'firebase/auth';

const firebaseConfig = {
  // TODO: Add your Firebase config here
};

const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);

export default function FirebaseFeaturesDemo() {
  const [user, setUser] = useState(null);
  const [messages, setMessages] = useState([]);

  // TODO: Add sign-in handler

  // TODO: Add real-time messages listener

  // TODO: Add function to add new message

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Firebase Features Demo</Text>
      <Button title="Sign In" onPress={() => { /* TODO */ }} />
      <Text style={styles.subtitle}>Messages:</Text>
      <FlatList
        data={messages}
        keyExtractor={item => item.id}
        renderItem={({ item }) => <Text style={styles.message}>- {item.text}</Text>}
      />
      <Button title="Add Message" onPress={() => { /* TODO */ }} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, marginTop: 40 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 10 },
  subtitle: { fontSize: 18, marginTop: 20, marginBottom: 10 },
  message: { fontSize: 16, marginVertical: 2 }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, onValue, push } from 'firebase/database';
import { getAuth, signInAnonymously, onAuthStateChanged } from 'firebase/auth';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);

export default function FirebaseFeaturesDemo() {
  const [user, setUser] = useState(null);
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });
    return unsubscribe;
  }, []);

  const handleSignIn = () => {
    signInAnonymously(auth).catch(error => {
      console.error('Sign in error:', error);
    });
  };

  useEffect(() => {
    const messagesRef = ref(database, 'messages');
    const unsubscribe = onValue(messagesRef, (snapshot) => {
      const data = snapshot.val() || {};
      const parsedMessages = Object.entries(data).map(([id, value]) => ({ id, text: value.text }));
      setMessages(parsedMessages);
    });
    return () => unsubscribe();
  }, []);

  const addMessage = () => {
    const messagesRef = ref(database, 'messages');
    push(messagesRef, { text: 'Welcome to Firebase!' });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Firebase Features Demo</Text>
      {!user ? (
        <Button title="Sign In" onPress={handleSignIn} />
      ) : (
        <Text>Signed in anonymously</Text>
      )}
      <Text style={styles.subtitle}>Messages:</Text>
      <FlatList
        data={messages}
        keyExtractor={item => item.id}
        renderItem={({ item }) => <Text style={styles.message}>- {item.text}</Text>}
      />
      <Button title="Add Message" onPress={addMessage} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, marginTop: 40 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 10 },
  subtitle: { fontSize: 18, marginTop: 20, marginBottom: 10 },
  message: { fontSize: 16, marginVertical: 2 }
});

This app uses Firebase Authentication to sign in users anonymously, which is simple and requires no user input. It listens to the Firebase Realtime Database for messages under the 'messages' path and updates the UI in real-time whenever data changes. The Add Message button pushes a new message with the text 'Welcome to Firebase!' to the database. This demonstrates Firebase's power for mobile backends: easy authentication, real-time data syncing, and simple database writes, all with minimal code.

Final Result
Completed Screen
---------------------------------
| Firebase Features Demo         |
|-------------------------------|
| Signed in anonymously          |
|                               |
| Messages:                     |
| - Welcome to Firebase!         |
|                               |
| [Add Message Button]           |
---------------------------------
Tapping 'Sign In' signs in the user anonymously and changes the button to a signed-in message
Messages list updates live when new messages are added
Tapping 'Add Message' adds a new 'Welcome to Firebase!' message to the list
Stretch Goal
Add a loading spinner while signing in and disable buttons during loading
💡 Hint
Use a state variable to track loading and conditionally render ActivityIndicator and disable buttons

Practice

(1/5)
1. Why do many mobile apps use Firebase as their backend service?
easy
A. Because Firebase only works for web apps, not mobile apps
B. Because Firebase handles user authentication, data storage, and notifications easily
C. Because Firebase requires you to manage your own servers
D. Because Firebase is a tool for designing app user interfaces

Solution

  1. Step 1: Understand Firebase features

    Firebase provides ready-made services like user login, database, and notifications for apps.
  2. Step 2: Compare options

    Only Because Firebase handles user authentication, data storage, and notifications easily correctly states Firebase's role in simplifying backend tasks without server management.
  3. Final Answer:

    Because Firebase handles user authentication, data storage, and notifications easily -> Option B
  4. Quick Check:

    Firebase simplifies backend = C [OK]
Hint: Remember Firebase is a backend service, not UI or server management [OK]
Common Mistakes:
  • Thinking Firebase requires managing servers
  • Confusing Firebase with UI design tools
  • Believing Firebase only works for web apps
2. Which of the following is the correct way to initialize Firebase in a React Native app?
easy
A. import { initializeApp } from 'firebase/app'; const app = initializeApp(config);
B. const app = new Firebase(config);
C. firebase.initialize(config);
D. import Firebase from 'firebase'; Firebase.start(config);

Solution

  1. Step 1: Recall Firebase initialization syntax

    Modern Firebase uses modular imports like 'initializeApp' from 'firebase/app'.
  2. Step 2: Check options for correct syntax

    Only import { initializeApp } from 'firebase/app'; const app = initializeApp(config); uses the correct import and initialization method.
  3. Final Answer:

    import { initializeApp } from 'firebase/app'; const app = initializeApp(config); -> Option A
  4. Quick Check:

    Use initializeApp from 'firebase/app' = A [OK]
Hint: Use modular imports with initializeApp for Firebase setup [OK]
Common Mistakes:
  • Using old Firebase syntax with 'new Firebase()'
  • Calling non-existent methods like Firebase.start()
  • Not importing initializeApp from 'firebase/app'
3. Given this React Native Firebase code snippet, what will be the output when fetching user data?
import { getFirestore, doc, getDoc } from 'firebase/firestore';
const db = getFirestore();
async function fetchUser() {
  const docRef = doc(db, 'users', 'user123');
  const docSnap = await getDoc(docRef);
  if (docSnap.exists()) {
    return docSnap.data().name;
  } else {
    return 'No user found';
  }
}
medium
A. Returns the entire user document object
B. Throws a syntax error because of missing await
C. Always returns 'No user found' regardless of data
D. Returns the user's name if found, otherwise 'No user found'

Solution

  1. Step 1: Analyze the async function fetchUser

    The function fetches a document from Firestore and checks if it exists.
  2. Step 2: Understand the return values

    If the document exists, it returns the 'name' field; otherwise, it returns 'No user found'.
  3. Final Answer:

    Returns the user's name if found, otherwise 'No user found' -> Option D
  4. Quick Check:

    Firestore doc exists? Return name : 'No user found' = D [OK]
Hint: Check docSnap.exists() before accessing data [OK]
Common Mistakes:
  • Forgetting to await getDoc causing runtime errors
  • Assuming getDoc returns data directly without checking existence
  • Returning entire docSnap instead of data().name
4. You wrote this code to send a push notification using Firebase Cloud Messaging, but it doesn't work:
import messaging from '@react-native-firebase/messaging';
async function sendNotification() {
  messaging().sendMessage({
    to: 'device_token',
    notification: { title: 'Hello', body: 'World' }
  });
}
What is the main error here?
medium
A. sendMessage is not a valid method on messaging()
B. Missing await before messaging().sendMessage()
C. Notification object keys should be uppercase
D. Device token must be an array, not a string

Solution

  1. Step 1: Check Firebase Messaging API

    The messaging() module does not have a sendMessage method for sending notifications.
  2. Step 2: Identify correct method usage

    Sending notifications requires using Firebase Cloud Functions or server-side API, not messaging().sendMessage.
  3. Final Answer:

    sendMessage is not a valid method on messaging() -> Option A
  4. Quick Check:

    messaging().sendMessage() invalid method = A [OK]
Hint: Check Firebase docs for correct messaging methods [OK]
Common Mistakes:
  • Assuming messaging() can send notifications directly
  • Forgetting to use server-side Firebase functions
  • Incorrect notification object format
5. You want to build a React Native app that lets users sign in with Google and store their profile data in Firebase Firestore. Which approach best uses Firebase to power this backend functionality?
hard
A. Manually create Google sign-in UI and store profiles in local device storage
B. Use Firebase Realtime Database only without authentication
C. Use Firebase Authentication for Google sign-in and Firestore to save user profiles automatically
D. Use Firebase Cloud Functions to handle UI and user sign-in

Solution

  1. Step 1: Identify Firebase services for authentication and data

    Firebase Authentication supports Google sign-in easily, and Firestore stores user data securely.
  2. Step 2: Evaluate options for backend power

    Use Firebase Authentication for Google sign-in and Firestore to save user profiles automatically uses Firebase's built-in services correctly, while others miss authentication or use wrong storage.
  3. Final Answer:

    Use Firebase Authentication for Google sign-in and Firestore to save user profiles automatically -> Option C
  4. Quick Check:

    Firebase Auth + Firestore = best backend approach [OK]
Hint: Combine Firebase Auth and Firestore for user data management [OK]
Common Mistakes:
  • Storing user data only locally without backend
  • Using Realtime Database without authentication
  • Misusing Cloud Functions for UI tasks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard