I have the following code snippet, and I expected it to result in an infinite loop due to a state update inside a fetch callback inside the body of the component without using ‘useEffect’. However, it’s not behaving as expected. Here’s the code:
function App() {
const [cartContent, setCartContent] = useState(null);
fetch("https://fakestoreapi.com/carts/6")
.then((resp) => resp.json())
.then((data) => {
setCartContent("test");
});
console.log(cartContent);
return <div className="cartContent">{cartContent}</div>;
}
export default App;
My understanding was that console.log(cartContent) should log the initial value of cartContent, then when setCartContent("test") is called inside the fetch callback, it should log "test", and this process should repeat indefinitely, creating an infinite loop.
Could someone please help me understand why this code doesn’t result in an infinite loop as expected? Any insights or explanations would be greatly appreciated. Thank you!
2
Answers
because this should be inside an useEffect, or any other effect pacakge like react query
"I’ve verified that your code is functioning properly. You might consider incorporating it within a useEffect hook for improved organization, but overall, the code looks solid. Please review the other components."
import React, { useState, useEffect } from "react";
function App() {
const [cartContent, setCartContent] = useState(null);
useEffect(() => {
}, []);
console.log(cartContent);
return {cartContent};
}
export default App;