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:
bashnpm install react-query
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;
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.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.useQuery
hook takes a query key ('images') and the fetchImages
function. It automatically handles data fetching, caching, and error handling.isLoading
), an error message if the request fails (error
), and the list of images once the data is available (data
).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.