Blog>
Snippets

Prefetching Data for Hydration

Provide an example of how to prefetch data with React Query to enhance the performance of server-side rendered applications. Include the use of the useQuery hook for prefetching data on the client side.
import { dehydrate, QueryClient, useQuery } from 'react-query';

async function fetchTodoById(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
}
Defines an asynchronous function to fetch a todo item by ID from a mock API and imports necessary functions from react-query.
export async function getServerSideProps(context) {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery(['todo', { id: 5 }], () => fetchTodoById(5));

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
}
Uses getServerSideProps to prefetch data on the server side for Next.js. It prefetches a todo item with ID 5 and passes the dehydrated state as props.
function Todo() {
  const { data, status } = useQuery(['todo', { id: 5 }], fetchTodoById);
  if (status === 'loading') return <div>Loading...</div>;
  if (status === 'error') return <div>Error fetching data</div>;

  return <div>{data.title}</div>;
}
Defines a React component that uses the useQuery hook to access the prefetched todo item on the client side and render it. It handles loading and error states.