How to use the React-Query library for caching API responses



Image not found!!

React-Query is a powerful library for managing and caching asynchronous data in React applications. It can be used to cache API responses efficiently and handle data fetching, caching, background updates, and stale data management seamlessly. Below is a basic example of how you can use React-Query to cache API responses:

  1. Install React-Query:
bash
npm install react-query
  1. Import necessary dependencies and set up React-Query in your application:
jsx
// App.js import React from 'react'; import { QueryClient, QueryClientProvider } from 'react-query'; import { ReactQueryDevtools } from 'react-query/devtools'; import ImageList from './ImageList'; const queryClient = new QueryClient(); const App = () => { return ( <QueryClientProvider client={queryClient}> <ImageList /> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> ); }; export default App;
  1. Define a component to fetch and display images using React-Query:
jsx
// ImageList.js import React from 'react'; import { useQuery } from 'react-query'; const fetchImages = async () => { const response = await fetch('https://api.example.com/images'); if (!response.ok) { throw new Error('Failed to fetch images'); } return response.json(); }; const ImageList = () => { const { data, error, isLoading } = useQuery('images', fetchImages); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> <h1>Images</h1> <ul> {data.map((image) => ( <li key={image.id}> <img src={image.url} alt={image.title} /> </li> ))} </ul> </div> ); }; export default ImageList;

In this example:

  • useQuery hook from React-Query is used to fetch and cache images from the API.
  • The fetchImages function is an asynchronous function that fetches images from the API. If the request is successful, it returns the JSON response; otherwise, it throws an error.
  • The useQuery hook takes a query key ('images') and the fetchImages function. It automatically handles data fetching, caching, and error handling.
  • The component renders a loading indicator while the data is being fetched (isLoading), an error message if the request fails (error), and the list of images once the data is available (data).
  1. You can customize the caching behavior, such as cache expiration and invalidation, using React-Query's options and query keys. Check out the React-Query documentation for more advanced usage and configuration options.

This example demonstrates a basic setup for caching API responses using React-Query. You can further enhance it with features like pagination, prefetching, and optimistic updates as per your application's requirements.