Reputation: 3
useEffect(() => {
onSnapshot(usersCollectionRef, (snapshot) => {
setUsers(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
});
});
I think this is the main cause of this problem because when I was using getDocs I was not getting any errors. I found out that using onSnapshot instead would help getting real-time updates on the website. But after letting the website run for a while, I get an error
React is out of memory.
Is there a way to fix this leak?
Upvotes: 0
Views: 352
Reputation: 85132
You're running this effect on every render, and never unsubscribing. Use a dependency array to only run the effect when relevant things change, and return an unsubscribe function to clean up when the component unmounts or the dependencies change.
useEffect(() => {
const unsubscribe = onSnapshot(usersCollectionRef, (snapshot) => {
setUsers(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
});
return unsubscribe; // <--- return teardown function
}, []); // <--- added dependency array
If usersCollectionRef can change, then the dependency array might need to be [usersCollectionRef]
Upvotes: 1