Blog>
Snippets

Prefetching Data with React Query and Async/Await

Example of how to prefetch data using React Query's prefetchQuery method combined with async/await syntax to improve data loading performance and user experience in React applications.
import { useQuery, prefetchQuery } from 'react-query';
import { fetchPosts } from './api';
Import useQuery and prefetchQuery from react-query, and the fetchPosts function from your API methods.
const queryClient = new QueryClient();
Create a new instance of QueryClient to manage the queries and cache.
async function prefetchPosts() {
  await queryClient.prefetchQuery('posts', fetchPosts);
}
Define an asynchronous function that utilizes the prefetchQuery method to load 'posts' data into the cache in advance.
useEffect(() => {
  prefetchPosts();
}, []);
Use the useEffect hook to call the prefetchPosts function when the component mounts, so the posts data is prefetched.
const { data, isLoading } = useQuery('posts', fetchPosts);
Inside your component, use the useQuery hook to fetch the data on-demand. Since the data might have already been prefetched, this could lead to immediate access to the data, improving user experience.