Blog>
Snippets

Using the useQuery Hook with Suspense

Showcase how to utilize the useQuery hook from React Query within a Suspense boundary for fetching data asynchronously, and display the data once it's loaded.
import { useQuery } from 'react-query';
import React, { Suspense } from 'react';
Imports the 'useQuery' hook from React Query library and 'Suspense' from React.
const fetchRecipes = async () => {
  const response = await fetch('https://example.com/api/recipes');
  if (!response.ok) throw new Error('Network response was not ok.');
  return response.json();
};
Defines an asynchronous function 'fetchRecipes' to fetch recipes data from an API.
function Recipes() {
  const { data, error, isError, isLoading } = useQuery('recipes', fetchRecipes, {
    suspense: true
  });

  if (isLoading) return <span>Loading...</span>;
  if (isError) return <span>Error: {error.message}</span>;

  return (
    <ul>{data.map(recipe => <li key={recipe.id}>{recipe.title}</li>)}</ul>
  );
}
Creates a 'Recipes' component that uses the 'useQuery' hook to fetch the recipes data, enabling Suspense by setting the 'suspense' option to true.
function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Recipes />
    </Suspense>
  );
}
Defines the 'App' component with Suspense boundary wrapping the 'Recipes' component. A fallback loading div is displayed while the data is being fetched.