skip to Main Content

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


  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.

    Login or Signup to reply.
  2. 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>
      )
    }
    
    Login or Signup to reply.
  3. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search