Search code examples
javascriptreactjsreact-hooksuse-effectreact-functional-component

why is an infinite loop created?


I'm trying to create a filter on data using React hooks. I really don't understand why this code creates an infinite loop when I call setEnteredFilter. LoadedData is an array containing some objects and and I only want the objects for which the id matches what I enter in the search bar.

const [enteredFilter, setEnteredFilter] = useState("");

  useEffect(() => {
    fetch("userConf_user.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (responseData) {
        let users = responseData.result.user;
        const loadedData = [];
        for (let obj in users) {
          loadedData.push(users[obj]);
        }
        onLoadUsers(loadedData); 

        setEnteredFilter(
          loadedData.filter((User) => {
            User === loadedData.map((user) => user.id);
          })
        ); 
      });
  }, [enteredFilter, onLoadUsers]);

  return (
    <section className="search">
      <Card>
        <div className="search-input">
          <label>search by Id: </label>
          <input
            type="text"
            value={enteredFilter}
            onChange={(Event) => setEnteredFilter(Event.target.value)}
          />
        </div>
      </Card>
    </section>
  );
});

Solution

  • Remove enteredFilter from the dependency array of the useEffect.

    , [/* REMOVE THIS enteredFilter, */ onLoadUsers]);
    

    The value is not referenced inside the useEffect, but because it changes the effect will run again causing the infinite loop.

    I suggest using ESLint and the eslint-plugin-react-hooks plugin. It would inform you in this case that enteredFilter is not referenced in the hook and therefore should be removed from the dependency array.