reactjsreact-hooksreact-strictmode

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


Solution

  • 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>
      )
    }