useQuery Hook for Data Fetching
What you'll learn: How to fetch GraphQL data with Apollo Client's useQuery hook, interpret loading and error states, and work with the query result object.
The Core Idea
After setting up Apollo Client, useQuery is your primary tool for fetching data from a GraphQL server. Unlike useMutation in TanStack Query, Apollo's useQuery executes automatically when the component mounts—it's declarative data fetching. You pass in a GraphQL query document, and Apollo handles the network request, caching, and state management for you.
How useQuery Works
The hook returns an object with several key properties:
loading: Boolean indicating if the query is in-flighterror: Contains error information if the request faileddata: The parsed GraphQL response when successful
This three-state pattern (loading → error/success) mirrors what you've seen in TanStack Query, but tailored for GraphQL's structured responses.
Typical Usage Pattern
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading users...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
The query executes immediately, and Apollo automatically updates your component when the data arrives—no manual state management needed.
The Result Object
Beyond loading, error, and data, the result object includes utilities like refetch() for manual re-fetching and networkStatus for granular loading states—tools you'll recognize from TanStack Query's patterns, adapted for GraphQL's schema-driven world.
Key Takeaway: useQuery provides declarative GraphQL data fetching with built-in loading/error handling—write the query, handle three states, and let Apollo manage the complexity.