Blog>
Snippets

Fetching Data with React Query's useQuery Hook

Show how to use React Query's useQuery hook to fetch data from an API, including handling loading, error, and data states.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchUserData = async () => {
  const { data } = await axios.get('https://api.example.com/user');
  return data;
};
Define a fetch function using axios to get user data from an API.
const UserProfile = () => {
  const { data, error, isLoading, isError } = useQuery('userData', fetchUserData);

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

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
};
Use the useQuery hook to fetch user data and dynamically handle loading, error, and data states.