'How to understand why my app is entering an infinite loop [closed]
I created a React app that does the following.
- Load CSV.
- Convert the CSV to JSON.
- Convert the JSON to HTML Table.
- On the button click do some processing.
Currently, my app is working as expected, but the issue is, it is going into an infinite loop on file load. I am not sure where I'm going wrong.
Here is the working code. Where am I going wrong?
Solution 1:[1]
It is going into an infinite loop on file load, because you put csvArray in useEffect's array, this means: every time csvArray changed the function fired again.
The solution:
useEffect(() => {
processCSV(csvData);
if (isProcessChange) {
setCsvArray(state => {
state.map((item) => {
var currRowValues = Object.entries(item);
var nd = currRowValues.reduce((a, [key, value]) => {
if (key === "sum") {
return a;
}
return a + value;
}, 0);
return { ...item, sum: nd };
});
});
}
}, [isProcessChange, csvData]);
And put setKeys in separate useEffect:
useEffect(() => {
setKeys(Object.keys(csvArray.length ? csvArray[0] : {}));
}, [csvArray]);
Solution 2:[2]
I haven't thoroughly debugged your code, but it looks like you have an infinite loop in your useEffect. When you upload a file, that causes the ProcessData component to render, and that component has a useEffect which depends on csvArray. However, that same useEffect also modifies csvArray, which would cause it to run again. Generally, a useEffect hook should not change any state values it depends on.
Also, instead of just linking to your code, it's nice if the question itself includes a minimal code sample that reproduces your problem.
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 | |
| Solution 2 | Raphael Serota |
