Reputation: 21
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
Upvotes: 0
Views: 1793
Reputation: 1
It is absolutely acceptable to utilize useEffect for the purpose you mentioned. While there is a concern for issues such as infinite loops, decreased performance efficiency, etc, these issues can be avoided through proper organization.
Regarding the running of useEffect being twice, this occurs in dev mode to aid in searching for any potential issues.
If you're keen on looking for alternatives, you can consider event handlers or perhaps context API's. Although there are still more options out there to consider.
Upvotes: 0
Reputation: 102547
It's okay to send an HTTP request in useEffect()
, but sometimes you might not need an effect:
If this logic is caused by a particular interaction, keep it in the event handler. If itβs caused by the user seeing the component on the screen, keep it in the Effect.
Effects let you synchronize a component with some external system (third-party API, network, etc).
See What are Effects and how are they different from events?
Upvotes: 0
Reputation: 75
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 :
// fetch data using react query
function Example() {
const { isPending, error, data } = useQuery({
queryKey: ['repoData'], // cache key
queryFn: () =>
fetch('https://api.github.com/repos/TanStack/query').then((res) =>
res.json(),
),
})
if (isPending) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>π {data.subscribers_count}</strong>{' '}
<strong>β¨ {data.stargazers_count}</strong>{' '}
<strong>π΄ {data.forks_count}</strong>
</div>
)
}
Upvotes: 2
Reputation: 1
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.
Upvotes: 0