Blog>
Snippets

Prefetching Data for Faster UI Transitions

Demonstrate prefetching data for a detail view when hovering over a list item, to enable instant data display upon navigation.
import { useQuery, queryClient } from 'react-query';
import React from 'react';
const fetchDetails = async (id) => {
  const response = await fetch(`/api/details/${id}`);
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
This code sets up the necessary imports from React and React Query libraries and defines the fetchDetails function, which receives an id and fetches the corresponding details from a server using the Fetch API.
function DetailsComponent({ id }) {
  const { data, isError, isLoading } = useQuery(['details', id], () => fetchDetails(id));

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error loading details.</div>;

  return <div>{JSON.stringify(data)}</div>;
}
This component uses the useQuery hook to fetch data for a detail view based on an id. It renders different elements based on the data fetching state: loading, error, or the data view.
function ListItem({ id, onMouseOver }) {
  return <div onMouseOver={() => onMouseOver(id)}>Item {id}</div>;
}
Defines a list item component that takes an id and a onMouseOver callback. When the item is hovered over, it triggers the callback with its id.
function List({ items }) {
  const handleMouseOver = (id) => {
    queryClient.prefetchQuery(['details', id], () => fetchDetails(id));
  };

  return (
    <div>{items.map(id => <ListItem key={id} id={id} onMouseOver={handleMouseOver} />)}</div>
  );
}
List component takes an array of item ids, and for each item, it renders a ListItem. When hovered over, it pre-fetches the details for that item by calling the handleMouseOver function, which triggers prefetching using the prefetchQuery method of the React Query's QueryClient.