📖 Scenario: You are building a simple React app that connects to Firebase to store and display user messages in real-time.This app will let users add messages, and you will see them appear instantly.
🎯 Goal: Create a React app that connects to Firebase Firestore, adds messages, and displays them live.
📋 What You'll Learn
Initialize Firebase in the React app with given config
Create a Firestore collection called messages
Add a message document to messages collection
Display messages from Firestore in real-time in the React component
💡 Why This Matters
🌍 Real World
Many apps use Firebase with React to build real-time chat, comments, or collaborative features easily without managing backend servers.
💼 Career
Understanding Firebase integration with React is valuable for frontend developers working on modern web apps that require real-time data and cloud backend.
Progress0 / 4 steps
1
Initialize Firebase in React
Create a file called firebaseConfig.js and write the Firebase initialization code. Import initializeApp from firebase/app. Use this exact config object: { apiKey: "AIzaSyA-ExampleKey", authDomain: "your-app.firebaseapp.com", projectId: "your-app", storageBucket: "your-app.appspot.com", messagingSenderId: "1234567890", appId: "1:1234567890:web:abcdef123456" }. Export the initialized app as app.
Firebase
Hint
Use initializeApp from firebase/app with the exact config object and export the app.
2
Setup Firestore and Add Message Function
In a new file called firebaseService.js, import getFirestore and collection, addDoc from firebase/firestore. Import app from ./firebaseConfig. Create a Firestore instance called db using getFirestore(app). Write an async function called addMessage that takes a text parameter and adds a document with field text to the messages collection. Export addMessage.
Firebase
Hint
Use getFirestore(app) to get Firestore instance. Use addDoc with collection(db, "messages") to add a message document.
3
Create React Component to Add Messages
In a React component file called MessageInput.js, import useState from react and addMessage from ./firebaseService. Create a functional component called MessageInput. Inside it, create a state variable input with setter setInput initialized to empty string. Add an input field bound to input and a button labeled "Send". On button click, call addMessage(input) and clear input. Export MessageInput.
Firebase
Hint
Use useState for input. Bind input field value and onChange. On button click, call addMessage and clear input.
4
Display Messages in Real-Time
Create a React component called MessageList in MessageList.js. Import useEffect, useState from react, and getFirestore, collection, onSnapshot from firebase/firestore. Import app from ./firebaseConfig. Inside MessageList, create a state variable messages initialized to empty array. Use useEffect to subscribe to real-time updates from the messages collection using onSnapshot. Update messages state with an array of message texts. Render a list of messages inside <ul> with each message in a <li>. Export MessageList.
Firebase
Hint
Use onSnapshot inside useEffect to listen to messages collection. Update state with message texts. Render messages in a list.
Practice
(1/5)
1. What is the main purpose of using Firebase with React in app development?
easy
A. To replace React's state management
B. To style React components with CSS
C. To compile React code faster
D. To add backend features like database and authentication easily
Solution
Step 1: Understand Firebase role
Firebase provides backend services like database and user authentication.
Step 2: Understand React role
React handles the user interface and frontend logic.
Final Answer:
To add backend features like database and authentication easily -> Option D
Quick Check:
Firebase adds backend features [OK]
Hint: Firebase adds backend, React builds UI [OK]
Common Mistakes:
Thinking Firebase is for styling
Confusing Firebase with React state
Assuming Firebase speeds up compilation
2. Which of the following is the correct way to initialize Firebase in a React app?
easy
A. import firebase from 'firebase'; firebase.init(config);
B. const app = new Firebase(config);
C. import { initializeApp } from 'firebase/app'; const app = initializeApp(config);
D. firebase.initialize(config);
Solution
Step 1: Check Firebase v9+ syntax
Firebase modular SDK uses initializeApp from 'firebase/app'.
Step 2: Verify correct import and call
import { initializeApp } from 'firebase/app'; const app = initializeApp(config); correctly imports and calls initializeApp with config.
Final Answer:
import { initializeApp } from 'firebase/app'; const app = initializeApp(config); -> Option C
Quick Check:
Use initializeApp from 'firebase/app' [OK]
Hint: Use modular import initializeApp from 'firebase/app' [OK]
Common Mistakes:
Using old firebase namespace import
Calling non-existent init or initialize methods
Creating Firebase instance with new keyword
3. Given this React code snippet using Firebase Firestore:
import { useEffect, useState } from 'react';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
const db = getFirestore();
getDocs(collection(db, 'users')).then(snapshot => {
const list = snapshot.docs.map(doc => doc.data().name);
setUsers(list);
});
}, []);
return <ul>{users.map(name => <li key={name}>{name}</li>)}</ul>;
}
What will this component display?
medium
A. A list of user names from the 'users' collection
B. An empty list because useEffect has no dependencies
C. A list of document IDs instead of names
D. A syntax error due to missing async keyword
Solution
Step 1: Analyze data fetching
useEffect runs once, fetches 'users' collection documents, maps to their 'name' field.
Step 2: Analyze rendering
Users state is set to list of names, rendered as list items in <ul>.
Final Answer:
A list of user names from the 'users' collection -> Option A
Quick Check:
Firestore docs mapped to names displayed [OK]
Hint: useEffect fetches once, maps docs to names [OK]
Common Mistakes:
Thinking useEffect needs async keyword directly
Confusing document IDs with data fields
Assuming empty list due to empty dependency array
4. What is wrong with this React Firebase code snippet?
B. useEffect callback should not be async function
C. setItems should be called outside useEffect
D. useState initial value must be null
Solution
Step 1: Identify async useEffect issue
React's useEffect callback cannot be async directly; it should call an async function inside.
Step 2: Confirm other parts
getDocs usage and setItems inside useEffect are correct; initial state as empty array is valid.
Final Answer:
useEffect callback should not be async function -> Option B
Quick Check:
Async function inside useEffect, not async callback [OK]
Hint: Never make useEffect callback async directly [OK]
Common Mistakes:
Making useEffect callback async directly
Thinking getDocs needs extra arguments
Believing setState must be outside useEffect
5. You want to build a React app that shows a live list of chat messages from Firebase Firestore. Which approach correctly updates the UI in real-time?
hard
A. Use Firestore's onSnapshot listener inside useEffect to update state on data changes
B. Call getDocs repeatedly every second inside useEffect to fetch new messages
C. Fetch messages once on component mount and never update state again
D. Use Firebase Realtime Database instead of Firestore for real-time updates
Solution
Step 1: Understand real-time update methods
Firestore provides onSnapshot to listen to live data changes and update UI immediately.
Step 2: Compare options
Use Firestore's onSnapshot listener inside useEffect to update state on data changes uses onSnapshot inside useEffect, which is best practice for real-time updates in React.
Final Answer:
Use Firestore's onSnapshot listener inside useEffect to update state on data changes -> Option A
Quick Check:
onSnapshot enables real-time UI updates [OK]
Hint: Use onSnapshot listener for live Firestore updates [OK]
Common Mistakes:
Polling with getDocs wastes resources
Fetching once misses updates
Confusing Firestore with Realtime Database necessity
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.