Reputation: 2822
I am developing an application where I need to make multiple API calls on page load and I need to alter the single state of the component upon each API call. The architecture looks like below.
const [stateForm, setStateForm] = useState(.....)
useEffect(()=>{
//FIRST API CALL
setStateForm({....})
},[])
useEffect(()=>{
//SECOND API CALL
setStateForm({....})
},[])
useEffect(()=>{
//THIRD API CALL
setStateForm({....})
},[])
//SO ON.....
My question is : Is it a okay to cause side effects in this way? Will altering state in each useEffect hook cause mutiple re-renders?
Upvotes: 0
Views: 737
Reputation: 3164
Is it a okay to cause side effects in this way?
There is nothing wrong so it's generally ok. But it's hard to say anything more definite beyond that - there is not much information to judge about this pattern of keeping overwriting the same state using outcome of a series of APIs which are generally async with unclear time to complete or fail.
Will altering state in each useEffect hook cause mutiple re-renders?
React can batch the series of re-renders triggered by setStateForm
so there will be only one re-render. If setStateForm
has to deal with Promises then React will not use batching, otherwise it may or may not.
Upvotes: 1