0

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?

5
  • You can also use promises for your calles. fetch().then(() => fetch()...) Commented Sep 24, 2019 at 10:53
  • each setStateForm cause multiply rerender. Look at answer: stackoverflow.com/questions/55521912/… Commented Sep 24, 2019 at 10:54
  • "Will altering state in each useEffect hook cause mutiple re-renders?" - almost certainly yes, unless the come simultaneously. Commented Sep 24, 2019 at 10:55
  • 2
    Also setStateForm does not merge state object as setState method on Component did. So each call will override entire stateForm. If you need to merge state use callback setStateForm(prevState => ({/* merge here */})) Commented Sep 24, 2019 at 10:56
  • Multiple useEffect only make sense if their dependencies are different - in your case it doesn't really make sense. Commented Sep 24, 2019 at 10:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.