+ 1
Why writing getProducts in the dependency list is creating infinite loop?
` import { useState, useEffect } from "react"; export const useFetch = (url) => { const [loading, setLoading] = useState(true); const [products, setProducts] = useState([]); const getProducts = async () => { console.log("inside getProducts"); const response = await fetch(url); const products = await response.json(); setProducts(products); setLoading(false); }; useEffect(() => { console.log("inside useEffect"); getProducts(); }, [url, getProducts]); return { loading, products }; }; ` Can anyone please explain why writing the getProducts function in the dependency list is creating an inifinite loop?
2 odpowiedzi
+ 1
I don't understand much but it has do with rendering of component and re declaration of function as what i understood from the following link.
https://stackoverflow.com/questions/62601538/react-useeffect-passing-a-function-in-the-dependency-array
Maybe i am wrong but from what i know setting a state to new value re renders the component and so getProduct function is declared again with a new reference . New reference would mean calling of useEffect function again.
But useEffect will be called on each render anyway which is confusing for me!
+ 1
Abhay Thanks :)