Feature Request: Add some COMPARISONS method for dependencies in the "useEffect" hook. For number datatype, the inbuilt comparison method works just fine but for "Arrays", it creates problem. I have shown an example below:
See original GitHub issueWhat I want to do?
I want to fetch all the users available form the database and add to the list. And at the same time if any new user is added from the backend or the admin panel, I want my list to get Updated without refreshing the page
`import React, { useState, useEffect } from ‘react’; import fetch from “isomorphic-unfetch”;
const AllUsers = () => { const [user, setUsers] = useState([]);
useEffect(() => {
fetchData();
console.log("I'm in");
}, [users]);
const fetchData = async () => {
const request = await fetch("/api/exam", {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
if (request.ok) {
const data = await request.json();
setUsers(data.active);
}
}
return (
<div>
{
users.map( value => { return <li>{value.name}</li> })
}
</div>
)
}
export default AllUsers`
What is the problem?
The code above turns into a infinite loop because every time , the comparison is shallow , i.e.,
const a = [1,2,3]; const b = [1,2,3]; console.log(a === b); // it is false
and every effect call its own effect.
What i suggest?
If we can compare just the size of the array of users from the previous state or compare some unique property of the data we are fetching and not compare the array as a whole, then we can avoid by entering into a infinite loop and also from refreshing the page often.
If the team can add optional COMPARISON method with the hook
Thanks for reading, Anand Dhawan (enthusiastic react developer)
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (1 by maintainers)
@hopper01 It’s an infinite loop because you’re re-fetching data each time the users change. Any reason why you’re re-fetching after fetching users?
Remove the
users
dependency here:To this, which only runs once on mount.
by reading the twitter comment of Dan Abramov, I think he is right, there is no need for this feature.