/firebase-tutorials

How to unsubscribe from Firestore snapshot listener?

Learn how to set up a Firestore snapshot listener and unsubscribe safely, with error handling and React integration for efficient real-time updates.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to unsubscribe from Firestore snapshot listener?

 
Step 1: Set Up Your Firestore Snapshot Listener
 

First, you need to set up a Firestore snapshot listener. This example will use the Firestore JavaScript SDK to demonstrate adding a listener to a Firestore collection. You'll typically do this inside a function in your app where you need real-time updates.

<pre><code class="hljs">
// Import Firestore
import { getFirestore, collection, onSnapshot } from "firebase/firestore"; 

// Set up Firestore
const db = getFirestore();

// Listen to a collection
const collectionRef = collection(db, 'your-collection-name');

const unsubscribe = onSnapshot(collectionRef, (snapshot) => {
  snapshot.docChanges().forEach((change) => {
    if (change.type === "added") {
      console.log("New data: ", change.doc.data());
    }
    if (change.type === "modified") {
      console.log("Modified data: ", change.doc.data());
    }
    if (change.type === "removed") {
      console.log("Removed data: ", change.doc.data());
    }
  });
});
</code></pre>

 
Step 2: Unsubscribe From the Listener
 

After setting up your listener, you'll need to unsubscribe when it's no longer needed—usually when a component is unmounted in a React app, or when a user navigates away in a web app.

The onSnapshot method returns an unsubscribe function which you can call to stop listening to changes.

<pre><code class="hljs">
// Call this function when you need to stop listening
unsubscribe();
</code></pre>

 
Step 3: Manage Unsubscription in React (Optional)
 

If you are using a library like React, it is common to start the listener when the component mounts and unsubscribe when the component unmounts. This ensures you do not listen for changes unnecessarily and manage the subscription efficiently.

<pre><code class="hljs">
import React, { useEffect } from 'react';
import { getFirestore, collection, onSnapshot } from "firebase/firestore"; 

const FirestoreComponent = () => {
  
  useEffect(() => {
    const db = getFirestore();
    const collectionRef = collection(db, 'your-collection-name');
    
    const unsubscribe = onSnapshot(collectionRef, (snapshot) => {
      snapshot.docChanges().forEach((change) => {
        if (change.type === "added") {
          console.log("New data: ", change.doc.data());
        }
        if (change.type === "modified") {
          console.log("Modified data: ", change.doc.data());
        }
        if (change.type === "removed") {
          console.log("Removed data: ", change.doc.data());
        }
      });
    });

    // Clean up the subscription to prevent memory leaks
    return () => unsubscribe();
  
  }, []);

  return <div>Firestore Data Listening...</div>
};

export default FirestoreComponent;
</code></pre>

 
Step 4: Error Handling
 

It's also a good practice to include error handling to ensure your app can handle any unexpected errors when listening or unsubscribing from Firestore.

<pre><code class="hljs">
// Example with error handling
try {
  const unsubscribe = onSnapshot(collectionRef, (snapshot) => {
    // Handle snapshot data
  }, (error) => {
    console.error("Error listening to collection: ", error);
  });
  
  // Unsubscribe safely
  return () => unsubscribe();

} catch (error) {
  console.error("Error unsubscribing: ", error);
}
</code></pre>

Now you have a comprehensive understanding of how to set up and unsubscribe from Firestore snapshot listeners. By following these steps, you can ensure that your app manages Firestore listeners efficiently and effectively.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022