const [resourceType, setResourceType] = useState("posts");
const [data, setData] = useState("");
useEffect(() => {
console.log("use effects called: " + resourceType);
fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
.then((result) => {
return result.json().then((data) => {
return {
data: data,
response: result.status,
};
});
//JSON.parse(result);
})
.then((data) => {
console.log("here");
setData(JSON.stringify(data));
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have the above code that is fetching dummy data from JSON placeholder URL and then updating the data variable (setData(JSON.stringify(data))). My question is, this implementation should go into an infinite loop as per my understanding of useEffect and useState react hook. Here is what I think should happen, the page renders it calls useEffect it updates data variable which will cause re-render of the component which should again call useEffect hence re-rending the component and the cycle goes on. But this is not happening and the useEffect is called only twice. Why is this happening?