The useQuery hook helps you get data from a GraphQL server easily inside your app. It runs a query and gives you the results to use.
0
0
useQuery hook in GraphQL
Introduction
When you want to show a list of items from a server, like products or users.
When you need to get details about something, like a user profile or a post.
When you want to update your app automatically if the data changes on the server.
When you want to handle loading and error states while waiting for data.
When you want to fetch data once and use it in your React component.
Syntax
GraphQL
const { data, loading, error } = useQuery(YOUR_GRAPHQL_QUERY, { variables: { /* your variables here */ }, fetchPolicy: 'cache-first' // optional });
useQuery returns an object with data, loading, and error.
You pass your GraphQL query and optional variables to useQuery.
Examples
This example fetches a list of users with their
id and name.GraphQL
import { useQuery, gql } from '@apollo/client'; const GET_USERS = gql` query GetUsers { users { id name } } `; const { data, loading, error } = useQuery(GET_USERS);
This example fetches one user by their
id using variables.GraphQL
const GET_USER_BY_ID = gql` query GetUserById($id: ID!) { user(id: $id) { id name email } } `; const { data, loading, error } = useQuery(GET_USER_BY_ID, { variables: { id: '123' } });
This example forces the query to always fetch fresh data from the server, ignoring cache.
GraphQL
const { data, loading, error } = useQuery(GET_USERS, { fetchPolicy: 'network-only' });
Sample Program
This React component uses useQuery to get a list of books from the server. It shows loading text while waiting, error if something goes wrong, and the list of books when ready.
GraphQL
import React from 'react'; import { useQuery, gql } from '@apollo/client'; const GET_BOOKS = gql` query GetBooks { books { id title author } } `; function BooksList() { const { data, loading, error } = useQuery(GET_BOOKS); if (loading) return <p>Loading books...</p>; if (error) return <p>Error loading books.</p>; return ( <ul> {data.books.map(book => ( <li key={book.id}>{book.title} by {book.author}</li> ))} </ul> ); } export default BooksList;
OutputSuccess
Important Notes
Always check loading and error before using data to avoid crashes.
You can pass variables to your query to get specific data.
useQuery automatically updates your component when data changes.
Summary
useQuery runs a GraphQL query and gives you data, loading, and error states.
Use it to fetch data inside React components easily.
Remember to handle loading and error states for a good user experience.