MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Executing GraphQL Queries with useQuery0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
13.1GraphQL Fundamentals and Apollo Client Setup13.2Executing GraphQL Queries with useQuery13.3GraphQL Mutations and Optimistic UI Updates13.4Real-Time GraphQL Subscriptions with WebSockets
HomeTutorialsReact.js for AdvancedExecuting GraphQL Queries with useQuery
GraphQL Mutations and Optimistic UI Updates

Executing GraphQL Queries with useQuery

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

The useQuery React hook is the primary mechanism for fetching GraphQL data in Apollo Client applications. It manages the complete query lifecycle—including loading states, error boundaries, data caching, background polling, and refetching—while integrating with TypeScript for end-to-end type safety.


1. Defining Typed Queries with gql

GraphQL documents are parsed using the gql tagged template literal:

1import { gql } from "@apollo/client";
2 
3export const GET_PROJECT_DETAILS = gql`
4 query GetProjectDetails($projectId: ID!) {
5 project(id: $projectId) {
6 id
7 title
8 status
9 budget
10 teamLead {
11 id
12 name
13 avatarUrl
14 }
15 tasks(limit: 10) {
16 id
17 title
18 completed
19 }
20 }
21 }
22`;

2. Using useQuery in a Component

1import React from "react";
2import { useQuery } from "@apollo/client";
3import { GET_PROJECT_DETAILS } from "./queries";
4 
5interface Task {
6 id: string;
7 title: string;
8 completed: boolean;
9}
10 
11interface ProjectData {
12 project: {
13 id: string;
14 title: string;
15 status: "ACTIVE" | "ARCHIVED" | "PENDING";
16 budget: number;
17 teamLead: {
18 name: string;
19 avatarUrl: string;
20 };
21 tasks: Task[];
22 };
23}
24 
25interface ProjectVars {
26 projectId: string;
27}
28 
29export function ProjectDetailView({ projectId }: { projectId: string }) {
30 const { data, loading, error, refetch, networkStatus } = useQuery<ProjectData, ProjectVars>(
31 GET_PROJECT_DETAILS,
32 {
33 variables: { projectId },
34 fetchPolicy: "cache-and-network", // Serves cached data instantly, updates from network in background
35 notifyOnNetworkStatusChange: true, // Enables tracking refetch spinners
36 }
37 );
38 
39 if (loading && !data) {
40 return (
41 <div className="p-8 text-cyan-400 flex items-center gap-2">
42 <span className="h-4 w-4 animate-spin rounded-full border-2 border-cyan-400 border-t-transparent" />
43 Loading project telemetry...
44 </div>
45 );
46 }
47 
48 if (error) {
49 return (
50 <div className="p-6 bg-rose-950/40 border border-rose-800 rounded-xl text-rose-300">
51 <h3 className="font-bold">Error loading project</h3>
52 <p className="text-xs mt-1">{error.message}</p>
53 <button
54 onClick={() => refetch()}
55 className="mt-3 px-3 py-1 bg-rose-800 hover:bg-rose-700 text-white rounded text-xs font-semibold"
56 >
57 Retry Query
58 </button>
59 </div>
60 );
61 }
62 
63 const { project } = data!;
64 
65 return (
66 <div className="p-8 bg-slate-900 text-white rounded-xl border border-slate-800">
67 <div className="flex justify-between items-start mb-6">
68 <div>
69 <h1 className="text-2xl font-bold">{project.title}</h1>
70 <span className="inline-block mt-1 px-2.5 py-0.5 rounded-full text-xs font-mono bg-cyan-950 text-cyan-400 border border-cyan-800">
71 Status: {project.status}
72 </span>
73 </div>
74 
75 <button
76 onClick={() => refetch()}
77 className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 rounded text-xs font-medium text-slate-300"
78 >
79 Refresh Data
80 </button>
81 </div>
82 
83 <div className="border-t border-slate-800 pt-4 space-y-2">
84 <h2 className="text-sm font-semibold text-slate-400">Milestone Tasks</h2>
85 {project.tasks.map((task) => (
86 <div key={task.id} className="flex items-center gap-3 p-2 bg-slate-950 rounded text-xs">
87 <span className={task.completed ? "text-emerald-400 line-through" : "text-slate-200"}>
88 {task.title}
89 </span>
90 </div>
91 ))}
92 </div>
93 </div>
94 );
95}

3. Understanding Fetch Policies

The fetchPolicy option controls how Apollo resolves data between the client cache and the network:

Fetch PolicyBehaviorBest Use Case
cache-first (Default)Checks cache; if found, never hits network. Hits network only on cache miss.Static or rarely changing reference data.
cache-and-networkReturns cached data immediately, then fetches from network in background and updates UI.High-activity dashboards requiring instant loads + fresh data.
network-onlyAlways queries the network, updating the cache with results.Critical financial balances or live checkout totals.
no-cacheAlways queries network and does not write to cache.Sensitive user data that should never persist in memory.

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the fetchPolicy: "cache-and-network" setting accomplish?
Question 2
Why is notifyOnNetworkStatusChange: true necessary when using refetch()?
Question 3
How do you pass dynamic parameters into a GraphQL query with useQuery?
Question 4
What happens if a component using useQuery unmounts before the network request resolves?
Question 5
What is the benefit of defining TypeScript interfaces for ProjectData and ProjectVars?
Next Lesson

GraphQL Mutations and Optimistic UI Updates

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
GraphQL Fundamentals and Apollo Client SetupGraphQL Mutations and Optimistic UI Updates

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext