DEV Community

Cover image for Using the react-query library
Kamran Ahmad
Kamran Ahmad

Posted on

Using the react-query library

Here is an example of using the react-query library to handle API calls in a React application:

Install the react-query library:

npm install react-query

Enter fullscreen mode Exit fullscreen mode

Wrap your application with the QueryClient provider:

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your application components here */}
    </QueryClientProvider>
  );
}

Enter fullscreen mode Exit fullscreen mode

Use the useQuery Hook to fetch data in your component:

import { useQuery } from 'react-query';

function Example() {
  const { data, status } = useQuery('data', () => axios.get('https://api.example.com/data'));

  if (status === 'loading') return <div>Loading...</div>;
  if (status === 'error') return <div>Error</div>;

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

You can also pass options to the useQuery Hook to customize the behavior of the query:

const { data, status } = useQuery('data', () => axios.get('https://api.example.com/data'), {
  retry: 3,
  retryDelay: 1000,
  stale

Enter fullscreen mode Exit fullscreen mode

Time: 60000,
});


In this example, the `useQuery` Hook takes 3 arguments: the key of the query, 
the function that returns the data, 
and the options. The key is used to identify the query and determine if it should be refetched or not. 
The function that returns the data can be a promise or a callback. 

The options are used to customize the behavior of the query, 
such as retrying the request on failure, or setting a stale time after which the data should be refetched.

It is important to note that `react-query` provides a lot of features such as caching, refetching, pagination, 
and more that help you to handle the API requests easily.

Please note that in this example, `https://api.example.com/data` should be replaced with the actual 
API endpoint you want to fetch data from.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)