question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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 issue

What 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:closed
  • Created 3 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
milesjcommented, Nov 24, 2020

@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:

useEffect(() => {
    fetchData();
    console.log("I'm in");

}, [users]);

To this, which only runs once on mount.

useEffect(() => {
    fetchData();
    console.log("I'm in");
}, []);
0reactions
hopper01commented, Dec 1, 2020

by reading the twitter comment of Dan Abramov, I think he is right, there is no need for this feature.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Under the Hood of React useEffect Dependencies
A deep dive into the dependencies array in React.useEffect(). What causes stale values from previous renders in React.
Read more >
Using the Effect Hook
Let's compare how classes and Hooks let us express such side effects. ... In React class components, the render method itself shouldn't cause...
Read more >
Hooks and state 102: the Dependency array in useEffect()
If you do have a dependency array, make sure that inside the useEffect, you're not setting state variables that are also dependencies.
Read more >
Useful React Hooks That You Can Use In Your Projects
Hooks organize side effects by functionality and it is possible to split a component into pieces based on the functionality. Confusing Classes.
Read more >
typescript-cheatsheet - GitHub Pages
A set of TypeScript related notes used for quick reference. The cheatsheet contains references to types, classes, decorators, and many other TypeScript ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found