React Query: Zero config data fetching
Still using useEffect to fetch data in your React apps ?
There is a better way to fetch data. Yes, you guessed it right "react-query".
React Query offers below major benefits:-
Recommended by LinkedIn
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
const queryClient = new QueryClient() // 1. Instantiate queryClient
export default function App() {
return (
<QueryClientProvider client={queryClient}> {/* 2. Wrap App inside QueryClientProvider
<Example /> & pass queryClient */}
</QueryClientProvider>
)
}
function Example() {
const { isLoading, error, data } = useQuery({ // 3. useQuery hook
queryKey: ['repoData'],
queryFn: () =>
fetch('https://api.github.com/repos/tannerlinsley/react-query').then(
(res) => res.json(),
),
})
if (isLoading) 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>
)
}
What's more its even compatible with your React Native apps. So what are you waiting for try React Query now and forgot the hassles of managing the loading, success & error states in your API calls.