Real-Time Listeners and Offline Persistence
Subscribe to a Firestore collection with onSnapshot, receive live updates in the UI, and enable offline persistence so the app reads cached data without a connection.
Real-Time Listeners vs One-Time Reads
Firestore offers two ways to read data: one-time reads with .get() and real-time listeners with .onSnapshot(). A real-time listener keeps a persistent connection open and fires your callback every time the document or query result changes, including the initial data load.
Use .get() when you only need data once (like loading user settings on app start). Use .onSnapshot() when data changes frequently and the UI must stay up to date, like a chat feed or a live score.
Listening to a Single Document
Call .onSnapshot(callback) on a DocumentReference to listen for changes to a specific document. The callback fires immediately with the current data and again whenever the document changes.
.onSnapshot() returns an unsubscribe function. Store it in a variable and call it in your useEffect cleanup to stop the listener when the component unmounts and avoid memory leaks.
import { useEffect, useState } from 'react';
import firestore from '@react-native-firebase/firestore';
export function usePost(postId: string) {
const [post, setPost] = useState(null);
useEffect(() => {
const unsubscribe = firestore()
.collection('posts')
.doc(postId)
.onSnapshot((snapshot) => {
if (snapshot.exists) {
setPost({ id: snapshot.id, ...snapshot.data() });
}
});
return unsubscribe; // Stop listener on unmount
}, [postId]);
return post;
}All lessons in this course
- Connecting React Native Firebase to Your Project
- Email and Phone Authentication with Firebase
- Reading and Writing Firestore Documents
- Real-Time Listeners and Offline Persistence