0
0
GraphqlHow-ToBeginner · 4 min read

How to Use useQuery Hook in Apollo Client

Use the useQuery hook from Apollo Client to fetch data in React components by passing a GraphQL query document. It returns an object with loading, error, and data properties to handle the query state and results.
📐

Syntax

The useQuery hook is called with a GraphQL query document and optional options. It returns an object containing the query's loading state, any error, and the fetched data.

  • query: The GraphQL query to execute.
  • variables: Optional variables for the query.
  • loading: Boolean indicating if the query is in progress.
  • error: Error object if the query failed.
  • data: The result data from the server.
javascript
const { loading, error, data } = useQuery(YOUR_GRAPHQL_QUERY, {
  variables: { /* optional variables */ },
  fetchPolicy: 'cache-first' // optional
});
💻

Example

This example shows how to use useQuery to fetch a list of books and display them. It handles loading and error states gracefully.

javascript
import React from 'react';
import { gql, useQuery } from '@apollo/client';

const GET_BOOKS = gql`
  query GetBooks {
    books {
      id
      title
      author
    }
  }
`;

function BooksList() {
  const { loading, error, data } = useQuery(GET_BOOKS);

  if (loading) return <p>Loading books...</p>;
  if (error) return <p>Error loading books: {error.message}</p>;

  return (
    <ul>
      {data.books.map(book => (
        <li key={book.id}>
          <strong>{book.title}</strong> by {book.author}
        </li>
      ))}
    </ul>
  );
}

export default BooksList;
Output
<ul><li><strong>The Great Gatsby</strong> by F. Scott Fitzgerald</li><li><strong>1984</strong> by George Orwell</li><li><strong>To Kill a Mockingbird</strong> by Harper Lee</li></ul>
⚠️

Common Pitfalls

Common mistakes when using useQuery include:

  • Not handling the loading state, causing UI to break before data arrives.
  • Ignoring error state, which can hide problems fetching data.
  • Passing incorrect or missing variables for queries that require them.
  • Using useQuery outside of an ApolloProvider, which causes errors.

Always check loading and error before rendering data.

javascript
/* Wrong way: ignoring loading and error */
const { data } = useQuery(GET_BOOKS);
return <div>{data.books[0].title}</div>;

/* Right way: handle loading and error */
const { loading, error, data } = useQuery(GET_BOOKS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <div>{data.books[0].title}</div>;
📊

Quick Reference

PropertyDescription
loadingTrue while the query is fetching data
errorContains error info if the query fails
dataThe data returned by the query
variablesOptional input variables for the query
fetchPolicyControls caching behavior (e.g., 'cache-first', 'network-only')

Key Takeaways

Use useQuery to fetch GraphQL data reactively in React components.
Always check loading and error before using data.
Pass required variables to queries that need them to avoid errors.
Wrap your app with ApolloProvider to enable useQuery.
Use fetchPolicy to control how Apollo Client caches and fetches data.