Blog>
Snippets

Using Prefetching with TanStack Ranger

Explain and show code for prefetching data using TanStack Ranger in a React components, improving the speed and responsiveness of the app.
import { useQuery } from 'tanstack/react-query';
First, import the useQuery hook from the TanStack React Query library.
import React from 'react';
import { QueryClient, QueryClientProvider } from 'tanstack/react-query';
Import React and necessary parts from tanstack/react-query to setup the query client.
const queryClient = new QueryClient();
Create a new QueryClient instance to manage the queries.
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyComponent />
    </QueryClientProvider>
  );
}
Wrap your components with QueryClientProvider and pass the query client instance to it.
const fetchData = async () => {
  const response = await fetch('https://example.com/data');
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
};
Define an asynchronous function to fetch your data from a remote source.
function MyComponent() {
  // Prefetch data when the component mounts
  React.useEffect(() => {
    queryClient.prefetchQuery(['dataKey'], fetchData);
  }, []);

  const { data, isLoading } = useQuery(['dataKey'], fetchData);

  if (isLoading) return <div>Loading...</div>;
  return (
    <div>
      <h1>Data loaded:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
Use the prefetchQuery method of the queryClient to prefetch data when MyComponent mounts. Then use the useQuery hook to fetch and display the data.