I heard that it is not a good practice to call an api inside useEffect, also thats why in dev mode useEffect runs twice.I am not sure about it, but if not useEffect, then what else?
Need fellow devs suggestions on it.Thank you
I heard that it is not a good practice to call an api inside useEffect, also thats why in dev mode useEffect runs twice.I am not sure about it, but if not useEffect, then what else?
Need fellow devs suggestions on it.Thank you
3
Answers
Calling an api in useEffect is okay as long as your component is not re-rendering Unnecessarily. Just make the dependency array empty or add the states/variables/props on which payload is changing.
It’s okay to use useEffect for simple api calls with simples states.
However, you can take a look at React Query. It’s better as it handle loading, errors, caching, and render only when necessary.
Example GET :
It’s okay to send an HTTP request in
useEffect()
, but sometimes you might not need an effect:See Sending a POST request
See What are Effects and how are they different from events?