TimothyBeckett
TimothyBeckett

Reputation: 79

VERY High number of reads in Firestore database in my React Project

I am making a simple CRUD app using react and firebase/firestore.

I currently have one collection of "products" with four records.

The home page loops over the products and displays them:

import React, { useEffect, useState } from 'react'
import { getDocs, collection } from "firebase/firestore"
import { db } from "../firebase-config"

const Home = () => {
  const [products, setProducts] = useState([])

  const productsCollectionRef = collection(db, "products") 

  useEffect(() => {
    const getProducts = async () =>{
      const data = await getDocs(productsCollectionRef)
      setProducts(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
    }

    getProducts()
  })

  return (
    <div>
      {products.map((product) => {
        return(
          <div>
            <div>{product.name}</div>
            <div>{product.sku}</div><br />
          </div>
        )
      })}
    </div>
  )
}

export default Home

I have played with the app for less than an hour, maybe have done about 10-20 refreshes and the number of reads jumped from 30ish to now over 35,000 within an hour.

At first, I thought this simple app would work with 50,000 free document reads a day but how in the world has it got to 35k+?

I let the page just sit there for an hour without doing anything and the number still rapidly increased.

Any idea what I can do to change this?

Thanks so much for your advice!

Let me know if you need any additional information...

Upvotes: 0

Views: 1118

Answers (1)

Antoine Gagnon
Antoine Gagnon

Reputation: 982

That is caused by your useEffect that does not have a dependency array.

When not provided a dependency array, useEffect will run on every render. In your useEffect, you update a state, which triggers a render which in turns triggers useEffect creating an infinite re-render loop.

Fix this by providing an empty dependency array to your useEffect so it only runs once.

  useEffect(() => {
    const getProducts = async () =>{
      const data = await getDocs(productsCollectionRef)
      setProducts(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
    }

    getProducts()
  }, [])

Upvotes: 5

Related Questions