React Query: Zero config data fetching
Pic credits : K. Mitch Hodge from Unsplash

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:-

  • Caching... (possibly the hardest thing to do in programming)
  • Deduping multiple requests for the same data into a single request
  • Updating "out of date" data in the background
  • Reflecting updates to data as quickly as possible
  • Performance optimizations like pagination and lazy loading data
  • Managing memory and garbage collection of server state
  • Memoizing query results with structural sharing

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

  1. Instantiate the QueryClient class.
  2. Wrap App component inside the QueryClientProvider and pass QueryClient instance as client.
  3. Now when you need to make an API call use the useQuery hook inside child components with below required parameters:-

  • queryKey: React Query manages query caching for you based on query keys. Query keys have to be an Array at the top level, and can be as simple as an Array with a single string, or as complex as an array of many strings and nested objects
  • queryFn: A query function can be literally any function that returns a promise. The promise that is returned should either resolve the data or throw an error.


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.

To view or add a comment, sign in

More articles by GOURAV SINGHAL

  • What's new in React 18? | #1 Automatic Batching

    What is Batching? Batching is when React groups multiple state updates into a single re-render for better performance…

  • Why React Hooks exist ?

    As a matter of fact React was already the most loved and wanted Web Framework by late 2018 when Hooks were first…

Others also viewed

Explore content categories