Home > Net >  React useEffects with setData is not getting into an infinite loop?
React useEffects with setData is not getting into an infinite loop?

Time:04-10

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?

CodePudding user response:

The data is the same the second time you call setData, so:

  • react doesn’t re-render your component, so
  • the effect doesn’t run, hence
  • no infinite loop.

You’d probably see an infinite loop if you weren’t stringifying the data.

CodePudding user response:

You need to pass the data object as the dependency array to useEffect()

useEffect(() => {
   ...your code
}, [data]);
  • Related