Abdullah Ibrâhim
Abdullah Ibrâhim

Reputation: 21

Should we call an API inside useEffect in React?

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

Answers (4)

saduprogb1101
saduprogb1101

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

Lin Du
Lin Du

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.

See Sending a POST request

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

Alexis
Alexis

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

Arslan Yousaf
Arslan Yousaf

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

Related Questions