Fetching and Caching Data with React Query
Demonstrate how to fetch a list of items from an API and cache the results using React Query to optimize performance.
import { useQuery } from 'react-query';
import axios from 'axios';
Import the useQuery hook from React Query and axios for making HTTP requests.
const fetchItems = async () => {
const { data } = await axios.get('https://api.example.com/items');
return data;
};
Define an asynchronous function fetchItems to fetch data from the API.
const ItemsList = () => {
const { data, isLoading, isError, error } = useQuery('items', fetchItems);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error: {error.message}</div>;
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
Create a functional component that uses the useQuery hook to fetch and display the items. It handles loading and error states.
export default ItemsList;
Export the ItemsList component for use in other parts of the application.