score:2

Accepted answer

You redeclare folderRef each render cycle, so if you include it in the useEffect hook's dependency array it will trigger render looping.

If you don't refer to folderRef anywhere else in the component then move it into the useEffect hook callback to remove it as an external dependnecy.

const [folders, setFolders] = useState([]);

useEffect(() => {
  const folderRef = collection(db, "folders");

  const getData = async () => {
    const data = await getDocs(folderRef);
    const folderData = data.docs.map((doc) => {
      return { id: doc.id, data: doc.data() };
    });
    console.log(folderData);
    setFolders(folderData);
  };

  getData();
}, []);

Or store it in a React ref so it can be safely referred to as a stable reference.

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]);

Update

I've gathered that you are updating the folders collection elsewhere in your app and want this component to "listen" for these changes. For this you can implement an onSnapshot listener.

It may look similar to the following:

const [folders, setFolders] = useState([]);

useEffect(() => {
  const unsubscribe = onSnapshot(
    collection(db, "folders"),
    (snapshot) => {
      const folderData = [];
      snapshot.forEach((doc) => {
        folderData.push({
          id: doc.id,
          data: doc.data(),
        });
      });
      setFolders(folderData);
    },
  );

  // Return cleanup function to stop listening to changes
  // on component unmount
  return unsubscribe;
}, []);

score:0

I think most Probably your useState function is like

const[folderRef , setFolders]=useState(Your Initial Value);

if this is the case then when ever you perform

useEffect(() => {
setFolder(Setting Anything Here)

....


},[folderRef])

React starts an infinity loop coz every time you use setFolder the FolderRef gets updated and the useEffect is forced to run again and it won't Stop .

use something like

const[folderRef , setFolders]=useState(Your Initial Value);
const[isLoading, setIsLoading]=useState(true);


useEffect(() => {
setFolder(Setting Anything Here)
setIsLoading(false)
....


},[])

...


return (
{ isLoading ? "Run the code you wanna run " : null  }
)

Related Query

More Query from same tag