DEV Community

Cover image for Building a Lightning-Fast CRUD App with Firebase Realtime Database & React
Debajit Mallick
Debajit Mallick

Posted on

1

Building a Lightning-Fast CRUD App with Firebase Realtime Database & React

Introduction

As a frontend developer, all we suffer is to get a backend, as most of the time we don't want to build a full-fledged backend. Firebase is a great saviour for choosing a BAAS (Backend As A Service). Firebase Realtime Database is a cloud-hosted NoSQL database that allows developers to store and sync data in real time. It is a great choice for building applications that require instant updates. In this blog, we will learn how to create a basic CRUD (Create, Read, Update, Delete) application using Firebase Realtime Database and React.

Prerequisites

Before we start, ensure you have the following installed:

  • Node.js (latest LTS version)
  • npm or yarn
  • A Firebase account with a project setup

Step 1: Setting Up Firebase

  1. Go to the Firebase Console.
  2. Create a new project.
  3. Navigate to Build > Realtime Database and click Create Database.
  4. Select the location and set the database rules to allow read and write for now:
   {
     "rules": {
       ".read": "true",
       ".write": "true"
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. In Project Settings > General, find your Firebase SDK configuration. Note down the API keys and database URL.

Step 2: Creating a React App

Run the following command to create a new React project using Vite:

npm create vite@latest 
Project name: firebase-crud
framework: react
language: JavaScript
...
cd firebase-crud
npm install firebase
Enter fullscreen mode Exit fullscreen mode

Step 3: Configuring Firebase in React

Inside your React project, create a firebase.js file:

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

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 firebaseApp = initializeApp(firebaseConfig);
const database = getDatabase(firebaseApp);

export default database;
Enter fullscreen mode Exit fullscreen mode

Step 4: Implementing CRUD Operations for users

Creating a Component

Inside src, create a components folder and add Users.js:

import React, { useState, useEffect } from "react";
import { ref, set, update, remove, onValue } from "firebase/database";
import database from "../firebase";

const Users = () => {
  const [data, setData] = useState({});
  const [name, setName] = useState("");

  useEffect(() => {
    const usersRef = ref(database, "users");
    onValue(usersRef, (snapshot) => {
      setData(snapshot.val() || {});
    });
  }, []);

  const handleCreate = () => {
    const id = Date.now().toString();
    set(ref(database, `users/${id}`), { name });
    setName("");
  };

  const handleUpdate = (id) => {
    update(ref(database, `users/${id}`), { name });
  };

  const handleDelete = (id) => {
    remove(ref(database, `users/${id}`));
  };

  return (
    <div>
      <h2>CRUD with Firebase</h2>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name"
      />
      <button onClick={handleCreate}>Add</button>

      <ul>
        {Object.keys(data).map((id) => (
          <li key={id}>
            {data[id].name}
            <button onClick={() => handleUpdate(id)}>Update</button>
            <button onClick={() => handleDelete(id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Users;
Enter fullscreen mode Exit fullscreen mode

Step 5: Rendering the Component

In App.js, import and use CrudOperations:

import React from "react";
import Users from "./components/Users";

function App() {
  return (
    <div className="App">
      <Users />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 6: Running the App

Start your React app using:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Conclusion

You have now created a simple CRUD app using Firebase Realtime Database and React! Now you can go to the next step by adding some more functionality where you add more fields for the user and create a user details page maybe. This example can be expanded with authentication, advanced validation, and real-time synchronization for a more robust application. If you like this blog and want to learn more about Frontend Development and Software Engineering you can follow me on Dev.to.

Image of Timescale

📊 Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench 🚀

Read full post →

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay