0

I am implementing a products directory using Firebase & React but there's something I just can't understand when I query my products. My landing page contains 4 tiles for the 4 main categories of products and I want to fetch the 3 most popular products for each category. For now I invoke 4 components which contain this function :

const [products, setProducts] = useState([]);

  async function fetchProducts() {
    const q = query(
      collection(db, "products"),
      where("category", "==", props.slug),
      orderBy("votes", "desc"),
      limit(3)
    );
    const querySnapshot = await getDocs(q);
    const prod = [];
    querySnapshot.forEach((doc) => {
      prod.push(doc.data());
    });
    setProducts(prod);
  }
  useEffect(() => {
    fetchProducts();
  });

My code works but I can't figure out the tremendous amount of reads anytime I hit npm run to test my code. There are only 5 products in the db but running my code on localhost for around 5 minutes generated 45k reads... any idea why that is ? Thanks a lot ! 44k reads in 5 minutes

allaxim
  • 36
  • 2
  • 3
    You forgot to pass a dependencies array to `useEffect`, which causes it to make a request on every render of the component. (Which, after the request is done, does a state update and render again - which accumulates up, every normal re-render by a prop change will start a new chain of updates and refetching). – Bergi Mar 30 '22 at 09:25
  • 1
    Look at the network panel in your devtools, you should be seeing those thousands of requests in there… – Bergi Mar 30 '22 at 09:26

0 Answers0