can someone help explain why this code is causing an infinite loop and what is the best approach to fixing it please and thank you.
I am assuming its because of the useEffect within the App component which is causing a re-render which then the useState also causes a render therefore causing an infinite loop. I think I am not understanding how useEffect and useState works properly.
import "./styles.css";
import React, { useEffect, useState } from "react";
interface IObject {
isLoading: boolean;
isError: boolean;
data: any[] | any;
}
function useHook1(): IObject {
console.log("hook 1 too many re-renders?");
return { isLoading: false, isError: false, data: [] };
}
function useHook2(): IObject {
const result = { isLoading: false, isError: false, data: "testing" };
console.log("hook 2 too many re-renders?");
return result;
}
export default function App() {
const { isLoading, isError, data } = useHook1();
const testResult = useHook2();
const [state, setState] = useState();
useEffect(() => {
console.log("inside useEffect within App")
setState(testResult.data)
}, [testResult])
console.log("too many re-renders?");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<p>{testing}</p>
</div>
);
}