Reading Data in Realtime
onSnapshot listens for Firestore data changes in realtime. It's extremely handy for chat messages, live dashboards, collaborative notes, and order status updates.
Code Example — Notes list realtime
javascript
import { getFirestore, collection, query, where, orderBy, onSnapshot } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';
const db = getFirestore();
const auth = getAuth();
function listenMyNotes(renderNotes) {
const user = auth.currentUser;
if (!user) return () => {};
const q = query(
collection(db, 'notes'),
where('ownerId', '==', user.uid),
orderBy('createdAt', 'desc')
);
const unsubscribe = onSnapshot(q, (snapshot) => {
const notes = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}));
renderNotes(notes);
});
return unsubscribe;
}What does this code do?
It reads the logged-in user's notes ordered by created time, and calls renderNotes again whenever the data changes. The UI can show the update without the user ever pressing refresh.
Common mistake
If you forget to call unsubscribe() once you no longer need the realtime listener, it keeps listening in the background and can hurt performance. In single-page apps, clean it up whenever the page or component changes.