Blog>
Snippets

Client-Side Data Fetching with the useQuery Hook

Demonstrate the use of React Query's useQuery hook to fetch data on the client-side and display it in a component, handling loading and error states.
import { useQuery } from 'react-query';
import React from 'react';
Import React and the useQuery hook from React Query.
const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) throw new Error('Network response was not ok.');
  return response.json();
};
Define a fetchData function that fetches data from a URL.
function ExampleComponent() {
  const { data, error, isLoading } = useQuery('dataKey', fetchData);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error has occurred: {error.message}</div>;

  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
Use the useQuery hook to fetch data inside a functional component. Handle loading, error, and success states.