Firebase is a comprehensive backend solution offered by Google that simplifies the process of building, managing, and growing applications. When developing mobile or web apps, handling the database, hosting, and authentication can be challenging tasks. Firebase addresses these challenges by providing a range of features.
Firebase Firestore, the database service provided by Firebase, helps manage and store app data efficiently. It eliminates the need to worry about designing and managing a database, as well as reduces bandwidth usage between the frontend and the database.
In addition to the database, Firebase offers authentication services, including popular methods such as username and password, email and password, and social media logins like Facebook, Twitter, and Google. With Firebase, implementing a secure and customizable authentication system becomes much easier, saving time and effort.
Firebase also provides hosting services, allowing you to deploy and host your app with ease. Whether you have a web application or need to store and serve static assets for mobile apps, Firebase Hosting ensures fast and reliable hosting, taking the hassle out of managing your own infrastructure.
Overall, Firebase offers a comprehensive solution for backend development, addressing the complexities of database management, authentication, and hosting. By leveraging Firebase’s capabilities, developers can focus on building the core functionality of their applications without worrying about the backend infrastructure.
Also firebase solves a very good problem of database it gives you a real-time database and in this article, we will see how to use firebase for database.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm i firebase
Project Structure: It will look like the following.

Project Structure
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Let’s first create two input fields namely Name and Password and with a Submit Button.
App.js
JavaScript
import React, { useState } from "react";
import "./App.css";
function App() {
const [customerName, setCustomerName] = useState("");
const [customerPassword, setCustomerPassword] = useState("");
return (
<div className="App">
<div className="App__form">
<input
type="text"
placeholder="Name"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={customerPassword}
onChange={(e) => setCustomerPassword(e.target.value)}
/>
<button>Submit</button>
</div>
</div>
);
}
export default App;
App.css
CSS
.App {
text-align: center;
height: 100vh;
display: grid;
place-items: center;
}
.App__form {
display: flex;
flex-direction: column;
}
input {
padding: 7px 11px;
border-radius: 3px;
border: none;
border-bottom: 1px solid gray;
margin: 20px;
outline: none;
}
button {
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 7px 12px;
border: none;
border-radius: 4px;
}
Now we will create the firebase project and create the firebase config file.
Steps to create a firebase project:
Step 1: Login in the firebase dashboard and  Click on Add Project Card.
Step 2: Enter your project name click on continue.
Step 3: In Configure Google Analytics select Default Account for Firebase and click on Create Project.
Step 4: Wait for firebase to create your project.
Step 5: Once the project is created go to the web icon as shown.
Step 6: Give the app nick name and select the firebase hosting checkbox if you want to host your app using firebase, register your app.
Step 7: Just install Firebase CLI if not installed yet using command given below on your VScode’s terminal
npm install -g firebase-tools
Step 8: Once done, just login into your firebase using the command given below using your command line or the terminal in VSCode.
firebase login
Step 9: Click on Continue to Console.
Step 10: Next go to your app click on the settings icon and at the bottom select the config option copy the config data. Go to your local project and create a file named firebase.js in the src folder and paste the config data along with few more lines in it as shown below.
Â
firebase.js
JavaScript
import firebase from "firebase";
const firebaseConfig = {
apiKey: "AIzaSyATKyTSJVN7-Zx60WQ66kkHo3nBhuMhYDs",
authDomain: "meteor-3fd94.firebaseapp.com",
projectId: "meteor-3fd94",
storageBucket: "meteor-3fd94.appspot.com",
messagingSenderId: "391620415322",
appId: "1:391620415322:web:6848292646d9e91e6e6d63",
measurementId: "G-69J20TCH7X",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export default db;
Now we have the config file ready and we just need to add code for the CRUD operations :
1. Create collection: Â To create a collection we simply use the db object we created in the firebase.js above. We simply import it in our file and use the collection method to locate the collection in which our data is to be stored after creation. In case your collection is nested in other collection you’ll have to write it like, db.collection(<parent-collection>).doc(<doc-id>).collection(<child-collection>) and so on. Now once we are in our collection we just simply add our data as an object.
App.js
JavaScript
import React, { useState } from "react";
import "./App.css";
import db from "./firebase";
function App() {
const [customerName, setCustomerName] = useState("");
const [customerPassword, setCustomerPassword] = useState("");
const submit = (e) => {
e.preventDefault();
db.collection("customersData").add({
name: customerName,
password: customerPassword,
});
setCustomerName("");
setCustomerPassword("");
};
return (
<div className="App">
<div className="App__form">
<input
type="text"
placeholder="Name"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={customerPassword}
onChange={(e) => setCustomerPassword(e.target.value)}
/>
<button onClick={submit}>Submit</button>
</div>
</div>
);
}
export default App;
Now we will test if our code works.
Once we see this page then we are all set. Just go to the localhost and enter the details and press submit and then again open Firestore Database in Firebase and you’ll see something like shown below :
So we can see our data as shown above
2. Read Operation: Now to read data, initial process is same i.e., importing db object. No we go to the collection where our data is stored that we want to read and then we use the onSnapshot method, which as the name suggests simply takes the snapshot every time any changes happen in the database. This function is responsible for the realtime feel that we get when we use firebase.
App.js
JavaScript
import React, { useState, useEffect } from "react";
import "./App.css";
import db from "./firebase";
function App() {
const [customerName, setCustomerName] = useState("");
const [customerPassword, setCustomerPassword] = useState("");
const [customersData, setCustomersData] = useState([]);
useEffect(() => {
db.collection("customersData").onSnapshot((snapshot) => {
setCustomersData(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
console.log({ customersData });
}, []);
const submit = (e) => {
e.preventDefault();
db.collection("customersData").add({
name: customerName,
password: customerPassword,
});
setCustomerName("");
setCustomerPassword("");
};
return (
<div className="App">
<div className="App__form">
<input
type="text"
placeholder="Name"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={customerPassword}
onChange={(e) => setCustomerPassword(e.target.value)}
/>
<button onClick={submit}>Submit</button>
</div>
<div className="App__DataDisplay">
<table>
<tr>
<th>NAME</th>
<th>PASSWORD</th>
</tr>
{customersData?.map(({ id, data }) => (
<tr key={id}>
<td>{data.name}</td>
<td>{data.password}</td>
</tr>
))}
</table>
</div>
</div>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

3. Update Operation: Let’s first a button that should update and the fields that should appear.Now after we have imported the db object from firebase.js we simply go to the collection where our data is stored that is to be updated and then we specify the doc we need to update as one collection has many documents so we have to specify that what doc is to be updated and then we simply use the update method and pass the updated object.
App.js
JavaScript
import React, { useState, useEffect } from "react";
import "./App.css";
import db from "./firebase";
function App() {
const [customerName, setCustomerName] = useState("");
const [customerPassword, setCustomerPassword] = useState("");
const [customersData, setCustomersData] = useState([]);
const [updatedCustomerName, setUpdatedCustomerName] = useState("");
const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState("");
const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState("");
useEffect(() => {
db.collection("customersData").onSnapshot((snapshot) => {
setCustomersData(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
}, []);
const submit = (e) => {
e.preventDefault();
db.collection("customersData").add({
name: customerName,
password: customerPassword,
});
setCustomerName("");
setCustomerPassword("");
};
const updateData = (e) => {
e.preventDefault();
db.collection("customersData").doc(dataIdToBeUpdated).update({
name: updatedCustomerName,
password: updatedCustomerPassword,
});
setUpdatedCustomerPassword("");
setUpdatedCustomerName("");
setDataIdToBeUpdated("");
};
return (
<div className="App">
{!dataIdToBeUpdated ? (
<div className="App__form">
<input
type="text"
placeholder="Name"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={customerPassword}
onChange={(e) => setCustomerPassword(e.target.value)}
/>
<button onClick={submit}>Submit</button>
</div>
) : (
<div className="App__Updateform">
<input
type="text"
placeholder="Name"
value={updatedCustomerName}
onChange={(e) => setUpdatedCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={updatedCustomerPassword}
onChange={(e) =>
setUpdatedCustomerPassword(e.target.value)}
/>
<button onClick={updateData}>Update</button>
</div>
)}
<div className="App__DataDisplay">
<table>
<tr>
<th>NAME</th>
<th>PASSWORD</th>
<th>Update</th>
</tr>
{customersData?.map(({ id, data }) => (
<tr key={id}>
<td>{data.name}</td>
<td>{data.password}</td>
<td>
<button
onClick={() => {
setDataIdToBeUpdated(id);
setUpdatedCustomerPassword(data.password);
setUpdatedCustomerName(data.name);
}}
>
Update
</button>
</td>
</tr>
))}
</table>
</div>
</div>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After updating the data you can check in your firebase dashboard if data get updated or not.
4. Delete Operation: Starting with the same thing, we import db object in our file then we simply go to the collection where our data is stored that is to be deleted and then we specify the doc we need to delete as one collection has many documents so we have to specify that what doc is to be deleted and then we simply call the delete method.
JavaScript
import React, { useState, useEffect } from "react";
import "./App.css";
import db from "./firebase";
function App() {
const [customerName, setCustomerName] = useState("");
const [customerPassword, setCustomerPassword] = useState("");
const [customersData, setCustomersData] = useState([]);
const [updatedCustomerName, setUpdatedCustomerName] = useState("");
const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState("");
const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState("");
useEffect(() => {
db.collection("customersData").onSnapshot((snapshot) => {
setCustomersData(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
}, []);
const submit = (e) => {
e.preventDefault();
db.collection("customersData").add({
name: customerName,
password: customerPassword,
});
setCustomerName("");
setCustomerPassword("");
};
const updateData = (e) => {
e.preventDefault();
db.collection("customersData").doc(dataIdToBeUpdated).update({
name: updatedCustomerName,
password: updatedCustomerPassword,
});
setUpdatedCustomerPassword("");
setUpdatedCustomerName("");
setDataIdToBeUpdated("");
};
const deleteData = (id) => {
db.collection("customersData").doc(id).delete();
};
return (
<div className="App">
{!dataIdToBeUpdated ? (
<div className="App__form">
<input
type="text"
placeholder="Name"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={customerPassword}
onChange={(e) => setCustomerPassword(e.target.value)}
/>
<button onClick={submit}>Submit</button>
</div>
) : (
<div className="App__Updateform">
<input
type="text"
placeholder="Name"
value={updatedCustomerName}
onChange={(e) => setUpdatedCustomerName(e.target.value)}
/>
<input
type="text"
placeholder="Password"
value={updatedCustomerPassword}
onChange={(e) =>
setUpdatedCustomerPassword(e.target.value)}
/>
<button onClick={updateData}>Update</button>
</div>
)}
<div className="App__DataDisplay">
<table>
<tr>
<th>NAME</th>
<th>PASSWORD</th>
<th>Update</th>
<th>Delete</th>
</tr>
{customersData?.map(({ id, data }) => (
<tr key={id}>
<td>{data.name}</td>
<td>{data.password}</td>
<td>
<button
onClick={() => {
setDataIdToBeUpdated(id);
setUpdatedCustomerPassword(data.password);
setUpdatedCustomerName(data.name);
}}
>
Update
</button>
</td>
<td>
<button
onClick={() => {
deleteData(id);
}}
>
Delete
</button>
</td>
</tr>
))}
</table>
</div>
</div>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After deleting the data you can check in your firebase dashboard if data get deleted or not.
Similar Reads
How to use events in ReactJS ?
Modern webpages rely on user interactions, triggering events like clicks or keypresses. React facilitates event handling with built-in methods, allowing developers to create listeners for dynamic interfaces and responses. JavaScript events, inherent to the DOM, use bubbling propagation by default, m
2 min read
How To Create a Website in ReactJS?
ReactJS is one of the most popular JavaScript libraries for building user interfaces. It allows you to create dynamic, reusable UI components and efficiently manage state and events. In this article, we'll walk through the steps to create a basic website using ReactJS. PrerequisitesNPM & Node.js
5 min read
How to push data into firebase Realtime Database using ReactJS ?
Firebase is a popular backend-as-a-service platform that provides various services for building web and mobile applications. One of its key features is the Realtime Database, which allows developers to store and sync data in real-time. In this article, we will explore how to push data into the Fireb
2 min read
How to Create a Basic Notes App using ReactJS ?
Creating a basic notes app using React JS is a better way to learn how to manage state, handle user input, and render components dynamically. In this article, we are going to learn how to create a basic notes app using React JS. A notes app is a digital application that allows users to create, manag
4 min read
Realtime Database vs Firestore
Realtime Database:Firebase is a real-time database that is a JSON datastore.It's totally unstructured which is a blessing and a curse.It is the Firebaseâs first and original cloud-based database.This real-time database demonstrates very low latency.Firebase Database Rules is the only security option
3 min read
How to Create an Unique ID in ReactJS ?
Generating an unique ID in React js is helpful in component identifiers in React applications. It can be used to separate and identify database records and as a key in many applications. How to Create Unique ID in ReactWe can create unique id in React With the help of UUID package, that generates un
3 min read
How to use x-grid-data-generator Module in ReactJS ?
Whenever we want to generate some data and build demos for the grid Component, we can use the x-grid-data-generator module in React JS. It has a large variety of data sets to play around with. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can us
2 min read
How to Fetch Data From an API in ReactJS?
ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, weâll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
5 min read
How to use DataGrid Component in ReactJS ?
A DataGrid Component helps in displaying the information in a grid-like format of rows and columns. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use DataGrid Component. Creating React Application And Inst
2 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read