useEffect is Executed in an endless loop react function component

Use of useEffect in React function component is common & frequent. Although useEffect is executed only once per render cycle, but you may have several state updates in your useEffect which cause a re-render. We always need to be careful & make sure we are not consuming too much memory. You can ideally put console.log() inside your useEffect() function and see how many times it is getting printed.

What if your useEffect() function is infinite loop?

The infinite loop is fixed by using dependency argument correctly while calling useEffect(callback, dependencies).

In following example, adding [value] parameter as a dependency of useEffect(..., [value])  call, the "login" state variable is updated only when [value] is changed. Doing this will solve the infinite loop problem:-

const [data, setData] = useState(null);
const [login, setLogin] = useState("githubusername");
useEffect(() => {
    console.log('useEffect()')
    fetch(`https://api.github.com/users/${login}`)
      .then(res => res.json())
      .then(setData)
      .catch(console.error);
  });

Instead:-

useEffect(() => {
    console.log('useEffect()')
    fetch(`https://api.github.com/users/${login}`)
      .then(res => res.json())
      .then(setData)
      .catch(console.error);
  }, [login]);

Also, If we pass an empty array to useEffect, it’s only executed after the first render.

useEffect(() => {
  // this is only executed once
}, [])