This useEffect is rendering one time if dependency array is empty but multiple times if i put folderRef in dependency array. I want to render the component only when I add or delete some folder. Please Help
import React, { useState, useEffect , useRef } from "react";
import { db } from "../firebase";
import { collection, getDocs } from "firebase/firestore";
import FolderData from "./FolderData";
function ShowFolder(props) {
const [folders, setFolders] = useState([]);
const folderRef = useRef(collection(db, "folders"));
useEffect(() => {
const getData = async () => {
const data = await getDocs(folderRef.current);
const folderData = data.docs.map((doc) => {
return { id: doc.id, data: doc.data() };
});
console.log(folderData);
setFolders(folderData);
};
getData();
}, [folderRef]);
return (
<div className="container md:px-4 mx-auto py-10">
<div className="md:grid lg:grid-cols-6 md:grid-cols-3 mlg:grid-cols-3 md:gap-10 space-y-6 md:space-y-0 px-1 md:px-0 mx-auto">
{folders.map((folder) => {
return (
<div key={folder.id}>
{folder.data.userId === props.userId && (
<div>
<FolderData key={folder.id} folder={folder} />
</div>
)}
</div>
);
})}
</div>
</div>
);
}
export default ShowFolder;
setFoldersandfolderRef. Can you provide more code? Especially thesetFoldersfunction? And it would be great to have a working example.setFoldersis likely the state updater function for thefolderDatastate. I think the relationship you are referring to would be between the dependencyfolderRefand thefolderDatastate since updating the state is what would trigger a rerender.folderRefin the dependency array of theuseEffectit means that on every render react checks if the dependency changed. If so theuseEffectis invoked. Since you update thefoldersstate inside theuseEffectit triggers a rerender. Thus I guesscollection(db, "folders")does return a different value each or multiple times that causes theuseEffectto execute and thus another rerender. And so on...