Home > Mobile >  Will setting up a Firestore onSnapshot listener in a useEffect with dependencies result in multiple
Will setting up a Firestore onSnapshot listener in a useEffect with dependencies result in multiple

Time:12-21

I'm using onSnapshot in a few components and I know I can return the unsubscribe function within useEffect and it will handle unsubscribing for me when the component unmounts and I don't have to worry about it.

But in my current use cases, useEffect doesn't have any dependencies, it's just:

useEffect(() => {
    const unsubscribe = db.collection(collectionName).doc(docId).onSnapshot(onNext, one rror);
    return unsubscribe;
}, []);

Now I have a case where I make a more complicated query to return a sorted and filtered list, and I want to subscribe to changes to the db but also need to update the query when the sort/filter params change.

Typically I'd do that with a useEffect like this:

useEffect(() => {
    const unsubscribe = db.collection( ... ).where(...sortOption something...).onSnapshot(...);
    return unsubscribe;    
}, [props.sortOption, props.filterTag]);

But in this scenario, would a change to props.sortOption or props.filterTag result in a new subscription being created without the old unsubscribe being called first?

CodePudding user response:

Yes, if you set up a Firestore onSnapshot listener in a useEffect with dependencies, and the dependencies change, it will result in a new subscription being created and the old one being unsubscribed because your useEffect will rerender again the moment your [props.sortOption, props.filterTag] change.

To fix this problem I think you can implement a local cache solution so there will be no unnecessary snapshots being created as Observing your code it looks like you are just sorting and filtering the collection.

You can use cache functionality of firestore to only create snapshot if any change occurred in the firestore db for more info follow this documentations

  • Related