I Got Stuck in an infinite loop in react.js. How to resolve this?
useEffect(() => {
fetch("https://react-http-d55a9-default-rtdb.firebaseio.com/todo.json")
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
setUsersList((prev) => [...prev]); //cause of infinite loop
});
}, [usersList]);
You are having an infinite loop because your useEffect
array of dependencies has usersList
on it and at the same time you are updating this variable inside your useEffect
function. So your useEffect
runs when the component mounts which updates your usersList
which makes the useEffect
run again which again updates your usersList
which makes it run again and so on...
To fix this, remove usersList
from the array of dependencies and have an empty array instead: []
. If you do this your useEffect
will run once, when your component mounts.