Skip to content
Advertisement

React – Too many re-renders when using props

I have been doing a project where I present a graph on the screen. Now, the data state within the App.js is being passed as a prop and then causes an infinite loop error.

If the data variable is within the Graph.js file and used and defined within the useState, then there is no issue.

I was a bit uncertain why this was happening as I am relatively new to react and javascript.

The goal is to add the data to the graph, it loads, then when I change the data within the App.js file, the page will automatically load again with the new data.

Any help/advice will be much appreciated 🙂

App.js

JavaScript

Graph.js

JavaScript

Advertisement

Answer

It’s because you’re updating the state on every render again and again. If you just simply call setData() inside the function, it will call this setter that invokes a re-render and triggers React to call your App function again.

If you want to have a default state, you can do it like below. If you want to update the state, it should be done by other actions, like the click of a button, fetching some data, etc.

Check out the demo below where I added a button that adds a new name to your nodes array:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement