Contact Us : +91 90331 80795

Blog Details

Breadcrub
Blog Detail

How to Build Offline-First React Apps Using IndexedDB and Service Workers

In today’s digital world, people expect apps to work smoothly at all times, even when the internet is slow or unavailable.
Imagine you are editing a document on your laptop while traveling, or using an app in an area with weak network coverage. The app should still work, right?
 
That’s exactly what Offline-First architecture aims to achieve.
 
With the help of React, IndexedDB, and Service Workers, you can build powerful Progressive Web Apps (PWAs) that continue to function both online and offline, keeping your users happy and productive.
 
 

What Does “Offline-First” Mean?

 
An offline-first app is built with the mindset that users may not always have an internet connection.
 
Instead of breaking or showing an error message, the app stores data locally and syncs it later when the internet connection is restored.
 
In simple words, offline-first means:
 
  • Your app works even without the internet

  • Data is saved locally in the browser

  • When online again, the app syncs that data to the server

 

Real-World Examples

 
Here are some examples of apps that use the offline-first approach:
 
  • Google Docs - lets you write and edit offline, and syncs changes later.

  • Spotify -  allows you to download songs and listen offline.

  • Notion - lets you create and edit notes offline; once online, it updates automatically.
These examples show how much users depend on apps that just work, even offline.
 
 

Tools You Will Use to Build an Offline-First React App

 
To make your React app offline-friendly, we will use these three key tools:
 

1. IndexedDB

 
A built-in browser database that allows storing data locally.
Think of it like a small local database that works even when there’s no internet.
 
Why it’s useful:
 
  • Can store large amounts of data (more than localStorage)

  • Works great for caching and offline queues

  • Supports complex data (objects, arrays, etc.)
We will use libraries like idb or dexie to simplify working with IndexedDB.
 

2. Service Workers

 
A Service Worker is a background script that runs separately from your main app.
It can:
 
  • Cache files (like HTML, JS, images) for offline use

  • Handle push notifications

  • Manage background sync tasks
It’s a must-have for any Progressive Web App (PWA).
 

3. React + Hooks

 
We will use React to build the UI and React Hooks to manage state and side effects (like loading or saving data).
 
 

Step 1: Set Up IndexedDB in React

 
Let’s start by installing the idb library, a simple wrapper around IndexedDB.
 
npm install idb

Now, create a file db.js inside your src folder.

This file will handle all local database operations, like creating the database, adding data, and fetching data.

import { openDB } from 'idb';

const DB_NAME = 'offlineAppDB';
const STORE_NAME = 'users';

export const initDB = async () => {
  return await openDB(DB_NAME, 1, {
    upgrade(db) {
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
      }
    },
  });
};

export const addUser = async (user) => {
  const db = await initDB();
  await db.add(STORE_NAME, user);
};

export const getUsers = async () => {
  const db = await initDB();
  return await db.getAll(STORE_NAME);
};
 

Explanation:

 
  • initDB() creates or opens a database named offlineAppDB.

  • upgrade() runs the first time and sets up a store named users.

  • addUser() saves a new record.
  • getUsers() fetches all stored users.
This makes your app capable of storing and reading data without needing a server.
 
 

Step 2: Using IndexedDB Inside Your React App

 
Now, let’s integrate the database functions into your main React component.
Create or update your App.js like this:
 
import React, { useEffect, useState } from "react";
import { addUser, getUsers } from "./db";

function App() {
  const [users, setUsers] = useState([]);
  const [name, setName] = useState("");

  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async () => {
    const storedUsers = await getUsers();
    setUsers(storedUsers);
  };

  const handleAddUser = async () => {
    await addUser({ name, createdAt: new Date() });
    setName("");
    loadUsers();
  };

  return (
    <div>
      <h1>Offline-First React App</h1>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={handleAddUser}>Add User</button>

      <ul>
        {users.map((u) => (
          <li key={u.id}>{u.name} - {u.createdAt.toString()}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

How It Works:

 
  • When the app loads, it calls getUsers() to show saved users.

  • When you add a new user, it’s stored in IndexedDB, not on a server.

  • Even if you disconnect from the internet, the data remains available.
Try adding users while offline, and you will see the data still appears!
 
 

Step 3: Add a Service Worker for Caching

 
Now, let’s make your app available even when offline by caching the essential files.
Create a service-worker.js file in your public folder.
 
const CACHE_NAME = "offline-cache-v1";
const urlsToCache = ["/", "/index.html", "/favicon.ico"];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(urlsToCache))
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

Then register the service worker inside index.js:

if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("/service-worker.js");
  });
}

 

What It Does:

 
  • The install event caches your app files.

  • The fetch event intercepts network requests and serves cached files when offline.

Now your app loads even without an internet connection!
 
 

Step 4: Sync Data When the Internet Returns

 

Now, let’s make your app smart; it should automatically sync data to the server when you are back online.

window.addEventListener("online", async () => {
  const pendingUsers = await getUsers();
  pendingUsers.forEach(async (user) => {
    await fetch("/api/users", {
      method: "POST",
      body: JSON.stringify(user),
      headers: { "Content-Type": "application/json" },
    });
  });
});
 

How It Works:

 
  • When the browser goes online, this event triggers.

  • It checks for locally saved users.

  • It sends them to your backend API automatically.
 
This ensures that no user data is lost, even if added offline.
 
 

Step 5: Make It a Progressive Web App (PWA)

 
To make your app installable and more like a native app, create a manifest.json file inside public.
 
{
  "name": "Offline React App",
  "short_name": "OfflineApp",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#317EFB",
  "icons": [
    {
      "src": "/icon.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}

Now your app can be installed on mobile or desktop like a native app!

 

Final Thoughts

 
By combining React, IndexedDB, and Service Workers, you can build powerful web apps that:
 
  • Store data locally when offline

  • Cache assets for faster load times

  • Sync data automatically when online
  • Deliver a native-like PWA experience
Offline-first apps not only improve user experience but also increase trust, engagement, and retention.
 

Collaboration with us

 
At Sparkle Web, we specialize in building Progressive Web Apps (PWAs) and offline-first solutions using React, Node.js, and cloud technologies.
 
Our goal is simple: to create apps that continue to function, even when your connection is unstable.
 
Did You Know?
 
  • 45% of users abandon apps that don’t work offline.

  • PWAs boost user engagement by 52%.

  • Companies using offline-first apps see 2x higher user retention.

That’s why businesses worldwide trust Sparkle Web to deliver fast, reliable, and scalable web solutions. Whether you want an offline React app, a cross-platform mobile app, or a real-time dashboard, Sparkle Web delivers end-to-end development, testing, and optimization services. Contact Us.

    Author

    • Owner

      Vaishali Gaudani

      Skilled React.js Developer with 3+ years of experience in creating dynamic, scalable, and user-friendly web applications. Dedicated to delivering high-quality solutions through innovative thinking and technical expertise.

    Contact Us

    Free Consultation - Discover IT Solutions For Your Business

    Unlock the full potential of your business with our free consultation. Our expert team will assess your IT needs, recommend tailored solutions, and chart a path to success. Book your consultation now and take the first step towards empowering your business with cutting-edge technology.

    • Confirmation of appointment details
    • Research and preparation by the IT services company
    • Needs assessment for tailored solutions
    • Presentation of proposed solutions
    • Project execution and ongoing support
    • Follow-up to evaluate effectiveness and satisfaction

    • Email: info@sparkleweb.in
    • Phone Number:+91 90331 80795
    • Address: 303 Capital Square, Near Parvat Patiya, Godadara Naher Rd, Surat, Gujarat 395010