Prefetching Data Using QueryKeys
Illustrate how to prefetch data for a smoother user experience by leveraging QueryKeys before a component mounts.
import { useQuery, useQueryClient } from 'react-query';
function prefetchTodos() {
const queryClient = useQueryClient();
return queryClient.prefetchQuery(['todos'], fetchTodos);
}
This piece of code demonstrates how to define a function `prefetchTodos` that uses `useQueryClient` from React Query to prefetch data for the query key ['todos']. The function `fetchTodos` is assumed to be an asynchronous function that fetches todo items from a server.
import React, { useEffect } from 'react';
import { useQuery } from 'react-query';
function Todos() {
const { data: todos, isLoading } = useQuery(['todos'], fetchTodos);
useEffect(() => {
prefetchTodos();
}, []);
if (isLoading) return <div>Loading...</div>;
return (
<div>{todos.map(todo => <p key={todo.id}>{todo.text}</p>)}</div>
);
}
This code shows how a React component `Todos` uses the `useEffect` hook to call `prefetchTodos` before the component mounts, ensuring that data is prefetched for a smoother user experience. It then uses the `useQuery` hook with the same query key ['todos'] to fetch the data for display in the component. `isLoading` is used to show a loading state while the data is being fetched.