I'm curious about the difference is using a useEffect hook to handle an API call vs just handling the API outside of an effect.
For example, with useEffect you might do something like
const MyComponent = () => {
const [myState, setMyState] = useState([])
const [trigger, setTrigger] = useState(false)
useEffect(() => {
const getData = async () => {
const callMyApi = await fetch('http://someApi.com')
setMyState(await callMyApi.json()
}
if(trigger) {
getData()
}
}, [trigger])
return (
<button onClick={setTrigger(true)}>Click me</button>
)
}
Vs, removing the useEffect
const MyComponent = () => {
const [myState, setMyState] = useState([])
const getData = async () => {
const callMyApi = await fetch('http://someApi.com')
setMyState(await callMyApi.json()
}
return (
<button onClick={getData()}>Click me</button>
)
}
That code isn't exact. But the point is, with hooks, are there pitfalls to not using useEffect to handle the fetching of data and updating state?