My post is more of a question than a problem. In react, in order to fetch data from an API we use the hook useEffect. But why not just work with states to manage the re-renderings ? (see example bellow)
import React from "react"
export default function App() {
const [starWarsData, setStarWarsData] = React.useState({})
const [isLoaded, setIsLoaded] = React.useState(false)
if (!isLoaded) {
const randomIndex = Math.floor(Math.random()*50)
fetch(`https://swapi.dev/api/people/${randomIndex}`)
.then(res => res.json())
.then(data => setStarWarsData(data))
setIsLoaded(true)
}
return (
<div>
<pre>{JSON.stringify(starWarsData, null, 2)}</pre>
<button onClick={() => setIsLoaded(false)}>Load random charachter</button>
</div>
)
}
As you can see, I manage the re-rendering with a simple if statement. Can you tell me why I should go with useEffect when fetching data and not the way presented above ?
Thanks in advance