0
0
FirebaseHow-ToBeginner · 3 min read

How to Use onSnapshot in Firestore for Real-Time Updates

Use onSnapshot in Firestore to listen for real-time updates to documents or collections. It takes a callback that runs every time data changes, providing the latest snapshot instantly. This keeps your app data fresh without manual refresh.
📐

Syntax

The onSnapshot method attaches a listener to a Firestore document or collection. It takes a callback function that receives a snapshot object whenever data changes.

  • docRef.onSnapshot(callback): Listens to a single document.
  • collectionRef.onSnapshot(callback): Listens to all documents in a collection.
  • The callback receives a snapshot with current data.
javascript
const unsubscribe = docRef.onSnapshot(snapshot => {
  console.log('Current data:', snapshot.data());
});
💻

Example

This example listens to a Firestore document and logs its data whenever it changes. It shows how onSnapshot keeps your app updated in real time.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, onSnapshot } from 'firebase/firestore';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

const docRef = doc(db, 'users', 'user123');

const unsubscribe = onSnapshot(docRef, (docSnapshot) => {
  if (docSnapshot.exists()) {
    console.log('User data:', docSnapshot.data());
  } else {
    console.log('No such document!');
  }
});

// Later, call unsubscribe() to stop listening.
Output
User data: { name: 'Alice', age: 30 }
⚠️

Common Pitfalls

Common mistakes when using onSnapshot include:

  • Not unsubscribing listeners, causing memory leaks.
  • Assuming the snapshot always has data without checking exists().
  • Using onSnapshot inside loops or repeatedly without cleanup.

Always save the unsubscribe function and call it when the listener is no longer needed.

javascript
/* Wrong: Not unsubscribing listener */
const unsubscribe = onSnapshot(docRef, snapshot => {
  console.log(snapshot.data());
});

// Listener stays active forever, causing performance issues

/* Right: Unsubscribe when done */
const unsubscribe = onSnapshot(docRef, snapshot => {
  console.log(snapshot.data());
});

// Later
unsubscribe();
📊

Quick Reference

MethodDescription
onSnapshot(docRef, callback)Listen to real-time updates on a single document
onSnapshot(collectionRef, callback)Listen to real-time updates on all documents in a collection
unsubscribe()Call the function returned by onSnapshot to stop listening
snapshot.exists()Check if the document exists before accessing data
snapshot.data()Get the current data from the snapshot

Key Takeaways

Use onSnapshot to get real-time updates from Firestore documents or collections.
Always check if the snapshot exists before reading data to avoid errors.
Save and call the unsubscribe function to stop listening and prevent memory leaks.
onSnapshot keeps your app data fresh without manual refresh or polling.