Home > OS >  Firebase's onSnapshot inside a useEffect; why does this infinitely loop?
Firebase's onSnapshot inside a useEffect; why does this infinitely loop?

Time:01-19

I'm getting documents from a collection in Firebase and I was wondering if the following useEffect would loop. Is this good practice?

  useEffect(() => {
    const routineRef = collection(db, "routines", session?.user?.id!, currentRoutine.name);
    const unsubscribe = onSnapshot(routineRef, (docsSnap) => {
      setWeightsHistorySnapshot(docsSnap.docs);
      // Infinite loop because this fills up my console
      console.log("Current data: ", docsSnap.docs);
    });
    return () => unsubscribe();
  }, [weightsHistorySnapshot, currentRoutine.name, session?.user?.id]);

CodePudding user response:

From the docs of onSnapshot

An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document.

You set the state using setWeightsHistorySnapshot, and have weightsHistorySnapshot in your dependencies array, which in turn changes on every call. This causes the hook to run over and over.

  • Related