What is Firestore Cache: Explanation and Usage
Firestore cache is a local storage on your device that saves copies of your Firestore data. It helps your app work faster and even offline by reading data from this local cache instead of always fetching from the internet.How It Works
Imagine you have a notebook where you write down important information you often need. Instead of asking your friend every time, you just check your notebook. Firestore cache works like that notebook. It keeps a local copy of your data on your device.
When your app asks for data, Firestore first looks in this local cache. If the data is there and fresh, it gives it to your app immediately. This makes your app faster because it doesn't have to wait for the internet. If the data is not in the cache or is outdated, Firestore fetches the latest data from the cloud and updates the cache.
This system also helps your app work offline. Even without internet, your app can read data from the cache and show it to the user. When the internet comes back, Firestore syncs any changes with the cloud.
Example
This example shows how to enable offline persistence so Firestore uses cache automatically. It also demonstrates reading data that may come from cache or server.
import { initializeApp } from 'firebase/app'; import { getFirestore, enableIndexedDbPersistence, collection, getDocs } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'your-api-key', authDomain: 'your-auth-domain', projectId: 'your-project-id' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); // Enable offline persistence (cache) enableIndexedDbPersistence(db).catch((err) => { if (err.code === 'failed-precondition') { console.log('Multiple tabs open, persistence can only be enabled in one tab at a time.'); } else if (err.code === 'unimplemented') { console.log('The browser does not support all features required to enable persistence'); } }); async function readData() { const querySnapshot = await getDocs(collection(db, 'users')); querySnapshot.forEach((doc) => { console.log(`${doc.id} =>`, doc.data()); }); } readData();
When to Use
Use Firestore cache when you want your app to load data quickly and work even without internet. For example, a chat app can show recent messages from cache while offline and sync new messages when online again.
It is also helpful in apps where users expect smooth experience without waiting for network calls, like note-taking apps or shopping lists.
However, if your app needs always the absolute latest data, you might want to fetch fresh data directly from the server sometimes.
Key Points
- Firestore cache stores data locally on the device for faster access.
- It enables offline support by serving data from cache when offline.
- Cache syncs with the cloud automatically when online.
- Enabling persistence is simple and recommended for most apps.
- Use cache to improve user experience with faster loading and offline use.