Using Query Prefetching
Example on how to prefetch data with React Query's `useQuery` and `prefetchQuery` methods, improving user experience by loading data before it's requested.
import { useQuery, useQueryClient } from 'react-query';
function Todos() {
const queryClient = useQueryClient();
// Prefetch the Todos whenever the mouse is over the Todos link
const prefetchTodos = () => {
queryClient.prefetchQuery('todos', fetchTodos)
};
return (
<div onMouseEnter={prefetchTodos}>
Show Todos
</div>
);
}
async function fetchTodos() {
// Fetch Todos from an API
const response = await fetch('/api/todos');
return response.json();
}
This code demonstrates how to prefetch data for a Todos component using React Query's `useQueryClient` and `prefetchQuery` methods. It preloads the data when the mouse enters the component area, reducing load time when the data is actually requested.
import { useQuery } from 'react-query';
function TodosList() {
const { data, status } = useQuery('todos', fetchTodos);
if (status === 'loading') return <div>Loading...</div>;
if (status === 'error') return <div>Error fetching data</div>;
return (
<ul>
{data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}
This segment of the code demonstrates how to request and display the Todos using React Query's `useQuery` hook. If the Todos have been prefetched, React Query will use the cached data instead of refetching it, hence making the data load instantly.