'Infinite Loop React

I'm new in React, and i have problems to show the content of an array. I have a state to store the data (initial value []). Then, I have a function to consume frmo an api with a get, then i store that data in the state, and finally, I iterate over the state to show it on the page. Everything's is ok, the function gives return the values, but in the console, the return is enter in a infinite loop, slowing down the browser.

Here I detach the code

The state where i store the values

const [projects, setProjects] = useState([]);

Function that consumes the api and save it in the state

const getData = async () => {
let allProjects = {};
const res = await axios.get(URL_BASE);
allProjects = res.data;
setProjects(allProjects);
console.log(projects);
};

useEffect to refresh the render when projects is change

useEffect(() => {
getData();
}, [projects]);

This is where i iterate

return (
<div>
  <p>La cantidadd de proyectos en total son:</p>
  {getData() && projects.map((proyecto) => <div>{proyecto.titulo}</div>)}
</div>
);


Solution 1:[1]

This useEffect basically says "any time projects changes, run getData()":

useEffect(() => {
  getData();
}, [projects]);

And running getData() changes projects:

const getData = async () => {
  //...
  setProjects(allProjects);
  //...
};

Thus the endless cycle.

It sounds like you just want to getData() once, when the component first loads. For that you can just use an empty dependency array:

useEffect(() => {
  getData();
}, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David