Prefetching Data with React Query
Demonstrate how to prefetch data using React Query's prefetchQuery method to improve loading times and user experience.
import { useQuery, useQueryClient } from 'react-query';
function PrefetchCarDetails() {
const queryClient = useQueryClient();
// Function to prefetch car details
const prefetchCarDetails = async (carId) => {
await queryClient.prefetchQuery(['carDetails', carId], fetchCarDetails);
};
return (
<div onMouseOver={() => prefetchCarDetails('123')}>Hover over me to prefetch car details!</div>
);
}
async function fetchCarDetails(carId) {
// Fetching logic for car details
const response = await fetch(`/api/cars/${carId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
This example demonstrates how to prefetch data using React Query's prefetchQuery method within a React component. When the user hovers over the specified div element, it triggers prefetching of car details for a certain car ID by calling `prefetchCarDetails`. The `fetchCarDetails` function simulates fetching data from an API endpoint. This approach improves user experience by loading data in advance before the actual request is made.