Fix linter error in useEffect without causing infinite loop

how do I fix the linter error in the dependency array, its asking for users to be added but that will cause an infinite loop.


export default function App() {
  const [users, setUsers] = useState([]);
  const [page, setCurrentPage] = useState(1);

  

  useEffect(() => {
    const fetchRandomUser = async (page) => {
      const response = await fetch(`https://randomuser.me/api?page=${page}
      `);
      const result = await response.json();
      const User = result.results[0];
      const Users = [...users, User];
      setUsers(Users);
    };
    fetchRandomUser(page);
  }, [page]);

  return (
    <div className="App">
      {users.length > 0 &&
        users.map((x) => (
          <>
            <UserComponent
              title={x.name.title}
              first={x.name.first}
              last={x.name.last}
              photo={x.picture.large}
              setCurrentPage={setCurrentPage}
              page={page}
            />
          </>
        ))}
    </div>
  );
}

const UserComponent = ({ title, first, last, photo, setCurrentPage, page }) => {
  return (
    <>
      <h1>
        {title} {first} {last}
      </h1>
      <img src={photo} alt="" />
      <button onClick={() => setCurrentPage((page) => page + 1)}>
        Add User
      </button>
    </>
  );
};

so how can I avoid passing users as a dependency?


what I tried:

but it didnt help me:
https://dmitripavlutin.com/react-useeffect-infinite-loop/

e.g. he says:

If you try his solution youll see the linter is also complaining about a missing dependency (that if you add it, it will cause an infinite loop, when you add the missing dependency ‘count’ because youll set the state, the count will change, its a dependency so it will be run again etc…)

I have no idea why hes giving the above examples when what he mentioned can be written as:


  const [value, setValue] = useState("");
  const [count, setCount] = useState(0);
  const onChange = ({ target }) => {
    setValue(target.value);
    setCount((count) => count + 1);
  };

  return (
    <div>
      <input type="text" value={value} onChange={onChange} />
      <div>Number of changes: {count}</div>
    </div>
  );

back to my orginal example with the fetch user, how can I avoid using this object as a dependency (satisfy the linter) ?

If you add the array directly to the state setter the tooltip should give you a hint about using a function for it.

setUsers([...users, User]);

React Hook useEffect has a missing dependency: ‘users’. Either include it or remove the dependency array. You can also do a functional update ‘setUsers(u => …)’ if you only need ‘users’ in the ‘setUsers’ call.

setUsers((users) => [...users, User]);

Doing that should remove the warning.

1 Like