Why writing getProducts in the dependency list is creating infinite loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

13th Sep 2021, 8:36 AM
NBinte
NBinte - avatar
2 Answers
+ 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!
13th Sep 2021, 9:50 AM
Abhay
Abhay - avatar
+ 1
Abhay Thanks :)
13th Sep 2021, 2:12 PM
NBinte
NBinte - avatar