Reputation: 245
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?
Upvotes: 1
Views: 3275
Reputation: 132
You can not have buttons for activating events in response to any detectable change in state of your app. To understand this consider the case of Chat App, two clients A and B are active and A sends message to B, now on receiving message from A the B client has to take some action, well how the B knows that it has received a message, to do this B could have made use of event listeners. Now you can custom create your event listener, but would you make custom event listeners for each different event?
Ideally you can make a general event listener which you can use for detecting change in state of app, well React already coded that event listener for you.
The only drawback for coding your own listener is waste of your time.
Upvotes: 0
Reputation: 495
Ideally,
if you want to make an API call on click of a button there is no need to use any hook like useEffect and useState, the way you did. your second approach is perfect and there is nothing wrong with that.
But if there is some specific usecase where it is required then there is nothing wrong in using hooks also you will just be making some extra rerenders but if that serves your use case then I guess that is fine too.
note:
<button onClick={setTrigger(true)}>Click me</button>
this is wrong, this setTrigger function will be call on mount of the component and I guess you might not want that.
you can instead do
<button onClick={()=>setTrigger(true)}>Click me</button>
OR
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>
)
}
Upvotes: 1